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 fanboyAnnoyanceListEnabled;
286 private boolean fanboySocialBlockingListEnabled;
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 (fanboyAnnoyanceListEnabled) {
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 (fanboySocialBlockingListEnabled){ // 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 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1395 mainWebView.requestFocus();
1400 public void onRestart() {
1401 // Run the default commands.
1404 // Apply the app settings if returning from the Settings activity..
1405 if (reapplyAppSettingsOnRestart) {
1406 // Apply the app settings.
1409 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1410 if (reloadOnRestart) {
1411 // Reload `mainWebView`.
1412 mainWebView.reload();
1414 // Reset `reloadOnRestartBoolean`.
1415 reloadOnRestart = false;
1418 // Reset the return from settings flag.
1419 reapplyAppSettingsOnRestart = false;
1422 // Apply the domain settings if returning from the Domains activity.
1423 if (reapplyDomainSettingsOnRestart) {
1424 // Reapply the domain settings.
1425 applyDomainSettings(formattedUrlString, false);
1427 // Reset `reapplyDomainSettingsOnRestart`.
1428 reapplyDomainSettingsOnRestart = false;
1431 // Load the URL on restart to apply changes to night mode.
1432 if (loadUrlOnRestart) {
1433 // Load the current `formattedUrlString`.
1434 loadUrl(formattedUrlString);
1436 // Reset `loadUrlOnRestart.
1437 loadUrlOnRestart = false;
1440 // Update the bookmarks drawer if returning from the Bookmarks activity.
1441 if (restartFromBookmarksActivity) {
1442 // Close the bookmarks drawer.
1443 drawerLayout.closeDrawer(GravityCompat.END);
1445 // Reload the bookmarks drawer.
1446 loadBookmarksFolder();
1448 // Reset `restartFromBookmarksActivity`.
1449 restartFromBookmarksActivity = false;
1452 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1453 updatePrivacyIcons(true);
1456 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1458 public void onResume() {
1459 // Run the default commands.
1462 // Resume JavaScript (if enabled).
1463 mainWebView.resumeTimers();
1465 // Resume `mainWebView`.
1466 mainWebView.onResume();
1468 // Resume the adView for the free flavor.
1469 if (BuildConfig.FLAVOR.contentEquals("free")) {
1470 BannerAd.resumeAd(adView);
1475 public void onPause() {
1476 // Pause `mainWebView`.
1477 mainWebView.onPause();
1479 // Stop all JavaScript.
1480 mainWebView.pauseTimers();
1482 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1483 if (BuildConfig.FLAVOR.contentEquals("free")) {
1484 BannerAd.pauseAd(adView);
1491 public boolean onCreateOptionsMenu(Menu menu) {
1492 // Inflate the menu; this adds items to the action bar if it is present.
1493 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1495 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1498 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1499 updatePrivacyIcons(false);
1501 // Get handles for the menu items.
1502 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1503 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1504 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1505 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1507 // Only display third-party cookies if SDK >= 21
1508 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1510 // Get the shared preference values. `this` references the current context.
1511 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1513 // Set the status of the additional app bar icons. The default is `false`.
1514 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1515 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1516 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1517 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1518 } else { //Do not display the additional icons.
1519 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1520 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1521 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1528 public boolean onPrepareOptionsMenu(Menu menu) {
1529 // Get handles for the menu items.
1530 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1531 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1532 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1533 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1534 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1535 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1536 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1537 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1538 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1539 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1540 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1541 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1543 // Set the text for the domain menu item.
1544 if (domainSettingsApplied) {
1545 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1547 addOrEditDomain.setTitle(R.string.add_domain_settings);
1550 // Set the status of the menu item checkboxes.
1551 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1552 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1553 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1554 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1555 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1557 // Enable third-party cookies if first-party cookies are enabled.
1558 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1560 // Enable `DOM Storage` if JavaScript is enabled.
1561 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1563 // Enable `Clear Cookies` if there are any.
1564 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1566 // Get a count of the number of files in the `Local Storage` directory.
1567 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1568 int localStorageDirectoryNumberOfFiles = 0;
1569 if (localStorageDirectory.exists()) {
1570 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1573 // Get a count of the number of files in the `IndexedDB` directory.
1574 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1575 int indexedDBDirectoryNumberOfFiles = 0;
1576 if (indexedDBDirectory.exists()) {
1577 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1580 // Enable `Clear DOM Storage` if there is any.
1581 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1583 // Enable `Clear Form Data` is there is any.
1584 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1585 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1587 // Enable `Clear Data` if any of the submenu items are enabled.
1588 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1590 // Initialize font size variables.
1591 int fontSize = mainWebView.getSettings().getTextZoom();
1592 String fontSizeTitle;
1593 MenuItem selectedFontSizeMenuItem;
1595 // Prepare the font size title and current size menu item.
1598 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1599 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1603 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1604 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1608 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1609 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1613 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1614 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1618 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1619 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1623 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1624 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1628 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1629 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1633 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1634 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1638 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1639 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1643 // Set the font size title and select the current size menu item.
1644 fontSizeMenuItem.setTitle(fontSizeTitle);
1645 selectedFontSizeMenuItem.setChecked(true);
1647 // Only show `Refresh` if `swipeToRefresh` is disabled.
1648 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1650 // Run all the other default commands.
1651 super.onPrepareOptionsMenu(menu);
1653 // Display the menu.
1658 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1659 @SuppressLint("SetJavaScriptEnabled")
1660 // removeAllCookies is deprecated, but it is required for API < 21.
1661 @SuppressWarnings("deprecation")
1662 public boolean onOptionsItemSelected(MenuItem menuItem) {
1663 // Get the selected menu item ID.
1664 int menuItemId = menuItem.getItemId();
1666 // Set the commands that relate to the menu entries.
1667 switch (menuItemId) {
1668 case R.id.add_or_edit_domain:
1669 if (domainSettingsApplied) { // Edit the current domain settings.
1670 // Reapply the domain settings on returning to `MainWebViewActivity`.
1671 reapplyDomainSettingsOnRestart = true;
1672 currentDomainName = "";
1674 // Create an intent to launch the domains activity.
1675 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1677 // Put extra information instructing the domains activity to directly load the current domain.
1678 domainsIntent.putExtra("LoadDomain", domainSettingsDatabaseId);
1681 startActivity(domainsIntent);
1682 } else { // Add a new domain.
1683 // Show the add domain `AlertDialog`.
1684 AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
1685 addDomainDialog.show(getSupportFragmentManager(), getResources().getString(R.string.add_domain));
1689 case R.id.toggle_javascript:
1690 // Switch the status of javaScriptEnabled.
1691 javaScriptEnabled = !javaScriptEnabled;
1693 // Apply the new JavaScript status.
1694 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1696 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1697 updatePrivacyIcons(true);
1699 // Display a `Snackbar`.
1700 if (javaScriptEnabled) { // JavaScrip is enabled.
1701 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1702 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1703 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1704 } else { // Privacy mode.
1705 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1708 // Reload the WebView.
1709 mainWebView.reload();
1712 case R.id.toggle_first_party_cookies:
1713 // Switch the status of firstPartyCookiesEnabled.
1714 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1716 // Update the menu checkbox.
1717 menuItem.setChecked(firstPartyCookiesEnabled);
1719 // Apply the new cookie status.
1720 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1722 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1723 updatePrivacyIcons(true);
1725 // Display a `Snackbar`.
1726 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1727 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1728 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1729 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1730 } else { // Privacy mode.
1731 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1734 // Reload the WebView.
1735 mainWebView.reload();
1738 case R.id.toggle_third_party_cookies:
1739 if (Build.VERSION.SDK_INT >= 21) {
1740 // Switch the status of thirdPartyCookiesEnabled.
1741 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1743 // Update the menu checkbox.
1744 menuItem.setChecked(thirdPartyCookiesEnabled);
1746 // Apply the new cookie status.
1747 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1749 // Display a `Snackbar`.
1750 if (thirdPartyCookiesEnabled) {
1751 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1753 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1756 // Reload the WebView.
1757 mainWebView.reload();
1758 } // Else do nothing because SDK < 21.
1761 case R.id.toggle_dom_storage:
1762 // Switch the status of domStorageEnabled.
1763 domStorageEnabled = !domStorageEnabled;
1765 // Update the menu checkbox.
1766 menuItem.setChecked(domStorageEnabled);
1768 // Apply the new DOM Storage status.
1769 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1771 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1772 updatePrivacyIcons(true);
1774 // Display a `Snackbar`.
1775 if (domStorageEnabled) {
1776 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1778 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1781 // Reload the WebView.
1782 mainWebView.reload();
1785 case R.id.toggle_save_form_data:
1786 // Switch the status of saveFormDataEnabled.
1787 saveFormDataEnabled = !saveFormDataEnabled;
1789 // Update the menu checkbox.
1790 menuItem.setChecked(saveFormDataEnabled);
1792 // Apply the new form data status.
1793 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1795 // Display a `Snackbar`.
1796 if (saveFormDataEnabled) {
1797 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1799 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1802 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1803 updatePrivacyIcons(true);
1805 // Reload the WebView.
1806 mainWebView.reload();
1809 case R.id.clear_cookies:
1810 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1811 .setAction(R.string.undo, v -> {
1812 // Do nothing because everything will be handled by `onDismissed()` below.
1814 .addCallback(new Snackbar.Callback() {
1816 public void onDismissed(Snackbar snackbar, int event) {
1818 // The user pushed the `Undo` button.
1819 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1823 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1825 // `cookieManager.removeAllCookie()` varies by SDK.
1826 if (Build.VERSION.SDK_INT < 21) {
1827 cookieManager.removeAllCookie();
1829 // `null` indicates no callback.
1830 cookieManager.removeAllCookies(null);
1838 case R.id.clear_dom_storage:
1839 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1840 .setAction(R.string.undo, v -> {
1841 // Do nothing because everything will be handled by `onDismissed()` below.
1843 .addCallback(new Snackbar.Callback() {
1845 public void onDismissed(Snackbar snackbar, int event) {
1847 // The user pushed the `Undo` button.
1848 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1852 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1854 // Delete the DOM Storage.
1855 WebStorage webStorage = WebStorage.getInstance();
1856 webStorage.deleteAllData();
1858 // Manually delete the DOM storage files and directories.
1860 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1861 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1863 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1864 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1865 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1866 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1867 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1868 } catch (IOException e) {
1869 // Do nothing if an error is thrown.
1877 case R.id.clear_form_data:
1878 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1879 .setAction(R.string.undo, v -> {
1880 // Do nothing because everything will be handled by `onDismissed()` below.
1882 .addCallback(new Snackbar.Callback() {
1884 public void onDismissed(Snackbar snackbar, int event) {
1886 // The user pushed the `Undo` button.
1887 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1891 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1893 // Delete the form data.
1894 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1895 mainWebViewDatabase.clearFormData();
1902 case R.id.font_size_twenty_five_percent:
1903 mainWebView.getSettings().setTextZoom(25);
1906 case R.id.font_size_fifty_percent:
1907 mainWebView.getSettings().setTextZoom(50);
1910 case R.id.font_size_seventy_five_percent:
1911 mainWebView.getSettings().setTextZoom(75);
1914 case R.id.font_size_one_hundred_percent:
1915 mainWebView.getSettings().setTextZoom(100);
1918 case R.id.font_size_one_hundred_twenty_five_percent:
1919 mainWebView.getSettings().setTextZoom(125);
1922 case R.id.font_size_one_hundred_fifty_percent:
1923 mainWebView.getSettings().setTextZoom(150);
1926 case R.id.font_size_one_hundred_seventy_five_percent:
1927 mainWebView.getSettings().setTextZoom(175);
1930 case R.id.font_size_two_hundred_percent:
1931 mainWebView.getSettings().setTextZoom(200);
1934 case R.id.display_images:
1935 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1936 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1937 mainWebView.reload();
1938 } else { // Images are not currently loaded automatically.
1939 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1942 // Set `onTheFlyDisplayImagesSet`.
1943 onTheFlyDisplayImagesSet = true;
1947 // Setup the share string.
1948 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1950 // Create the share intent.
1951 Intent shareIntent = new Intent();
1952 shareIntent.setAction(Intent.ACTION_SEND);
1953 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1954 shareIntent.setType("text/plain");
1957 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1960 case R.id.find_on_page:
1961 // Hide the URL app bar.
1962 supportAppBar.setVisibility(View.GONE);
1964 // Show the Find on Page `RelativeLayout`.
1965 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1967 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1968 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1969 findOnPageEditText.postDelayed(() -> {
1970 // Set the focus on `findOnPageEditText`.
1971 findOnPageEditText.requestFocus();
1973 // Display the keyboard. `0` sets no input flags.
1974 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1979 // Get a `PrintManager` instance.
1980 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1982 // Convert `mainWebView` to `printDocumentAdapter`.
1983 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1985 // Remove the lint error below that `printManager` might be `null`.
1986 assert printManager != null;
1988 // Print the document. The print attributes are `null`.
1989 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1992 case R.id.view_source:
1993 // Launch the Vew Source activity.
1994 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1995 startActivity(viewSourceIntent);
1998 case R.id.add_to_homescreen:
1999 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2000 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2001 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2003 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2007 mainWebView.reload();
2011 // Don't consume the event.
2012 return super.onOptionsItemSelected(menuItem);
2016 // removeAllCookies is deprecated, but it is required for API < 21.
2017 @SuppressWarnings("deprecation")
2019 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2020 int menuItemId = menuItem.getItemId();
2022 switch (menuItemId) {
2028 if (mainWebView.canGoBack()) {
2029 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2030 navigatingHistory = true;
2032 // Load the previous website in the history.
2033 mainWebView.goBack();
2038 if (mainWebView.canGoForward()) {
2039 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2040 navigatingHistory = true;
2042 // Load the next website in the history.
2043 mainWebView.goForward();
2048 // Get the `WebBackForwardList`.
2049 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2051 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2052 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2053 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2056 case R.id.downloads:
2057 // Launch the system Download Manager.
2058 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2060 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2061 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2063 startActivity(downloadManagerIntent);
2067 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2068 reapplyDomainSettingsOnRestart = true;
2069 currentDomainName = "";
2071 // Launch `DomainsActivity`.
2072 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2073 startActivity(domainsIntent);
2077 // Set the flag to reapply app settings on restart when returning from Settings.
2078 reapplyAppSettingsOnRestart = true;
2080 // Set the flag to reapply the domain settings on restart when returning from Settings.
2081 reapplyDomainSettingsOnRestart = true;
2082 currentDomainName = "";
2084 // Launch `SettingsActivity`.
2085 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2086 startActivity(settingsIntent);
2090 // Launch `GuideActivity`.
2091 Intent guideIntent = new Intent(this, GuideActivity.class);
2092 startActivity(guideIntent);
2096 // Launch `AboutActivity`.
2097 Intent aboutIntent = new Intent(this, AboutActivity.class);
2098 startActivity(aboutIntent);
2101 case R.id.clearAndExit:
2102 // Get a handle for `sharedPreferences`. `this` references the current context.
2103 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2105 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2108 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2109 // The command to remove cookies changed slightly in API 21.
2110 if (Build.VERSION.SDK_INT >= 21) {
2111 cookieManager.removeAllCookies(null);
2113 cookieManager.removeAllCookie();
2116 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2118 // We have to use two commands because `Runtime.exec()` does not like `*`.
2119 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2120 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2121 } catch (IOException e) {
2122 // Do nothing if an error is thrown.
2126 // Clear DOM storage.
2127 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2128 // Ask `WebStorage` to clear the DOM storage.
2129 WebStorage webStorage = WebStorage.getInstance();
2130 webStorage.deleteAllData();
2132 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2134 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2135 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2137 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2138 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2139 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2140 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2141 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2142 } catch (IOException e) {
2143 // Do nothing if an error is thrown.
2148 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2149 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2150 webViewDatabase.clearFormData();
2152 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2154 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2155 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2156 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2157 } catch (IOException e) {
2158 // Do nothing if an error is thrown.
2163 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2164 // `true` includes disk files.
2165 mainWebView.clearCache(true);
2167 // Manually delete the cache directories.
2169 // Delete the main cache directory.
2170 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2171 // Delete the secondary `Service Worker` cache directory.
2172 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2173 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2174 } catch (IOException e) {
2175 // Do nothing if an error is thrown.
2179 // Clear SSL certificate preferences.
2180 mainWebView.clearSslPreferences();
2182 // Clear the back/forward history.
2183 mainWebView.clearHistory();
2185 // Clear `formattedUrlString`.
2186 formattedUrlString = null;
2188 // Clear `customHeaders`.
2189 customHeaders.clear();
2191 // Detach all views from `mainWebViewRelativeLayout`.
2192 mainWebViewRelativeLayout.removeAllViews();
2194 // Destroy the internal state of `mainWebView`.
2195 mainWebView.destroy();
2197 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2198 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2199 if (clearEverything) {
2201 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2202 } catch (IOException e) {
2203 // Do nothing if an error is thrown.
2207 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2208 if (Build.VERSION.SDK_INT >= 21) {
2209 finishAndRemoveTask();
2214 // Remove the terminated program from RAM. The status code is `0`.
2219 // Close the navigation drawer.
2220 drawerLayout.closeDrawer(GravityCompat.START);
2225 public void onPostCreate(Bundle savedInstanceState) {
2226 super.onPostCreate(savedInstanceState);
2228 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2229 drawerToggle.syncState();
2233 public void onConfigurationChanged(Configuration newConfig) {
2234 super.onConfigurationChanged(newConfig);
2236 // Reload the ad for the free flavor if we are not in full screen mode.
2237 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2239 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2241 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2242 adView = findViewById(R.id.adview);
2245 // `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:
2246 // https://code.google.com/p/android/issues/detail?id=20493#c8
2247 // ActivityCompat.invalidateOptionsMenu(this);
2251 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2252 // Store the `HitTestResult`.
2253 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2256 final String imageUrl;
2257 final String linkUrl;
2259 // Get a handle for the `ClipboardManager`.
2260 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2262 // Remove the lint errors below that `clipboardManager` might be `null`.
2263 assert clipboardManager != null;
2265 switch (hitTestResult.getType()) {
2266 // `SRC_ANCHOR_TYPE` is a link.
2267 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2268 // Get the target URL.
2269 linkUrl = hitTestResult.getExtra();
2271 // Set the target URL as the title of the `ContextMenu`.
2272 menu.setHeaderTitle(linkUrl);
2274 // Add a `Load URL` entry.
2275 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
2280 // Add a `Copy URL` entry.
2281 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2282 // Save the link URL in a `ClipData`.
2283 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2285 // Set the `ClipData` as the clipboard's primary clip.
2286 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2290 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2291 menu.add(R.string.cancel);
2294 case WebView.HitTestResult.EMAIL_TYPE:
2295 // Get the target URL.
2296 linkUrl = hitTestResult.getExtra();
2298 // Set the target URL as the title of the `ContextMenu`.
2299 menu.setHeaderTitle(linkUrl);
2301 // Add a `Write Email` entry.
2302 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2303 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2304 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2306 // Parse the url and set it as the data for the `Intent`.
2307 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2309 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2310 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2313 startActivity(emailIntent);
2317 // Add a `Copy Email Address` entry.
2318 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2319 // Save the email address in a `ClipData`.
2320 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2322 // Set the `ClipData` as the clipboard's primary clip.
2323 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2327 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2328 menu.add(R.string.cancel);
2331 // `IMAGE_TYPE` is an image.
2332 case WebView.HitTestResult.IMAGE_TYPE:
2333 // Get the image URL.
2334 imageUrl = hitTestResult.getExtra();
2336 // Set the image URL as the title of the `ContextMenu`.
2337 menu.setHeaderTitle(imageUrl);
2339 // Add a `View Image` entry.
2340 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2345 // Add a `Download Image` entry.
2346 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2347 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2348 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2349 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2351 // Store the image URL for use by `onRequestPermissionResult()`.
2352 downloadImageUrl = imageUrl;
2354 // Show a dialog if the user has previously denied the permission.
2355 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2356 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2357 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2359 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2360 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2361 } else { // Show the permission request directly.
2362 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2363 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2365 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2366 // Get a handle for the download image alert dialog.
2367 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2369 // Show the download image alert dialog.
2370 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2375 // Add a `Copy URL` entry.
2376 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2377 // Save the image URL in a `ClipData`.
2378 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2380 // Set the `ClipData` as the clipboard's primary clip.
2381 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2385 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2386 menu.add(R.string.cancel);
2390 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2391 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2392 // Get the image URL.
2393 imageUrl = hitTestResult.getExtra();
2395 // Set the image URL as the title of the `ContextMenu`.
2396 menu.setHeaderTitle(imageUrl);
2398 // Add a `View Image` entry.
2399 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2404 // Add a `Download Image` entry.
2405 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2406 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2407 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2408 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2410 // Store the image URL for use by `onRequestPermissionResult()`.
2411 downloadImageUrl = imageUrl;
2413 // Show a dialog if the user has previously denied the permission.
2414 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2415 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2416 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2418 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2419 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2420 } else { // Show the permission request directly.
2421 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2422 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2424 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2425 // Get a handle for the download image alert dialog.
2426 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2428 // Show the download image alert dialog.
2429 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2434 // Add a `Copy URL` entry.
2435 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2436 // Save the image URL in a `ClipData`.
2437 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2439 // Set the `ClipData` as the clipboard's primary clip.
2440 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2444 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2445 menu.add(R.string.cancel);
2451 public void onAddDomain(AppCompatDialogFragment dialogFragment) {
2452 // Reapply the domain settings on returning to `MainWebViewActivity`.
2453 reapplyDomainSettingsOnRestart = true;
2454 currentDomainName = "";
2456 // Get the new domain name `String` from `dialogFragment`.
2457 EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
2458 String domainNameString = domainNameEditText.getText().toString();
2460 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2461 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2462 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2464 // Create the domain and store the database ID in `currentDomainDatabaseId`.
2465 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
2467 // Create an intent to launch the domains activity.
2468 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2470 // Put extra information instructing the domains activity to directly load the current domain.
2471 domainsIntent.putExtra("LoadDomain", newDomainDatabaseId);
2474 startActivity(domainsIntent);
2478 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2479 // Get the `EditTexts` from the `dialogFragment`.
2480 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2481 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2483 // Extract the strings from the `EditTexts`.
2484 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2485 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2487 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2488 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2489 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2490 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2492 // Display the new bookmark below the current items in the (0 indexed) list.
2493 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2495 // Create the bookmark.
2496 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2498 // Update `bookmarksCursor` with the current contents of this folder.
2499 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2501 // Update the `ListView`.
2502 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2504 // Scroll to the new bookmark.
2505 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2509 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2510 // Get handles for the views in `dialogFragment`.
2511 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2512 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2513 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2515 // Get new folder name string.
2516 String folderNameString = createFolderNameEditText.getText().toString();
2518 // Get the new folder icon `Bitmap`.
2519 Bitmap folderIconBitmap;
2520 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2521 // Get the default folder icon and convert it to a `Bitmap`.
2522 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2523 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2524 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2525 } else { // Use the `WebView` favorite icon.
2526 folderIconBitmap = favoriteIconBitmap;
2529 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2530 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2531 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2532 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2534 // Move all the bookmarks down one in the display order.
2535 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2536 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2537 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2540 // Create the folder, which will be placed at the top of the `ListView`.
2541 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2543 // Update `bookmarksCursor` with the current contents of this folder.
2544 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2546 // Update the `ListView`.
2547 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2549 // Scroll to the new folder.
2550 bookmarksListView.setSelection(0);
2554 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2555 // Get the shortcut name.
2556 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2557 String shortcutNameString = shortcutNameEditText.getText().toString();
2559 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2560 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2562 // Setup the shortcut intent.
2563 Intent shortcutIntent = new Intent();
2564 shortcutIntent.setAction(Intent.ACTION_VIEW);
2565 shortcutIntent.setData(Uri.parse(formattedUrlString));
2567 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2568 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2570 // Add the required fields to the shortcut info builder.
2571 shortcutInfoBuilder.setIcon(favoriteIcon);
2572 shortcutInfoBuilder.setIntent(shortcutIntent);
2573 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2575 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2576 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2580 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2581 switch (downloadType) {
2582 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2583 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2584 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2587 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2588 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2589 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2595 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
2596 switch (requestCode) {
2597 case DOWNLOAD_FILE_REQUEST_CODE:
2598 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2599 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2601 // On API 23, displaying the fragment must be delayed or the app will crash.
2602 if (Build.VERSION.SDK_INT == 23) {
2603 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2605 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2608 // Reset the download variables.
2610 downloadContentDisposition = "";
2611 downloadContentLength = 0;
2614 case DOWNLOAD_IMAGE_REQUEST_CODE:
2615 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2616 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2618 // On API 23, displaying the fragment must be delayed or the app will crash.
2619 if (Build.VERSION.SDK_INT == 23) {
2620 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2622 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2625 // Reset the image URL variable.
2626 downloadImageUrl = "";
2632 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2633 // Download the image if it has an HTTP or HTTPS URI.
2634 if (imageUrl.startsWith("http")) {
2635 // Get a handle for the system `DOWNLOAD_SERVICE`.
2636 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2638 // Parse `imageUrl`.
2639 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2641 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2642 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2643 if (firstPartyCookiesEnabled) {
2644 // Get the cookies for `imageUrl`.
2645 String cookies = cookieManager.getCookie(imageUrl);
2647 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2648 downloadRequest.addRequestHeader("Cookie", cookies);
2651 // Get the file name from the dialog fragment.
2652 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2653 String imageName = downloadImageNameEditText.getText().toString();
2655 // Specify the download location.
2656 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2657 // Download to the public download directory.
2658 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2659 } else { // External write permission denied.
2660 // Download to the app's external download directory.
2661 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2664 // Allow `MediaScanner` to index the download if it is a media file.
2665 downloadRequest.allowScanningByMediaScanner();
2667 // Add the URL as the description for the download.
2668 downloadRequest.setDescription(imageUrl);
2670 // Show the download notification after the download is completed.
2671 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2673 // Remove the lint warning below that `downloadManager` might be `null`.
2674 assert downloadManager != null;
2676 // Initiate the download.
2677 downloadManager.enqueue(downloadRequest);
2678 } else { // The image is not an HTTP or HTTPS URI.
2679 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2684 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2685 // Download the file if it has an HTTP or HTTPS URI.
2686 if (downloadUrl.startsWith("http")) {
2687 // Get a handle for the system `DOWNLOAD_SERVICE`.
2688 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2690 // Parse `downloadUrl`.
2691 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2693 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2694 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2695 if (firstPartyCookiesEnabled) {
2696 // Get the cookies for `downloadUrl`.
2697 String cookies = cookieManager.getCookie(downloadUrl);
2699 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2700 downloadRequest.addRequestHeader("Cookie", cookies);
2703 // Get the file name from the dialog fragment.
2704 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2705 String fileName = downloadFileNameEditText.getText().toString();
2707 // Specify the download location.
2708 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2709 // Download to the public download directory.
2710 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2711 } else { // External write permission denied.
2712 // Download to the app's external download directory.
2713 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2716 // Allow `MediaScanner` to index the download if it is a media file.
2717 downloadRequest.allowScanningByMediaScanner();
2719 // Add the URL as the description for the download.
2720 downloadRequest.setDescription(downloadUrl);
2722 // Show the download notification after the download is completed.
2723 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2725 // Remove the lint warning below that `downloadManager` might be `null`.
2726 assert downloadManager != null;
2728 // Initiate the download.
2729 downloadManager.enqueue(downloadRequest);
2730 } else { // The download is not an HTTP or HTTPS URI.
2731 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2736 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2737 // Get handles for the views from `dialogFragment`.
2738 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2739 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2740 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2742 // Store the bookmark strings.
2743 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2744 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2746 // Update the bookmark.
2747 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2748 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2749 } else { // Update the bookmark using the `WebView` favorite icon.
2750 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2751 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2752 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2753 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2755 // Update the bookmark and the favorite icon.
2756 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2759 // Update `bookmarksCursor` with the current contents of this folder.
2760 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2762 // Update the `ListView`.
2763 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2767 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2768 // Get handles for the views from `dialogFragment`.
2769 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2770 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2771 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2772 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2774 // Get the new folder name.
2775 String newFolderNameString = editFolderNameEditText.getText().toString();
2777 // Check if the favorite icon has changed.
2778 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2779 // Update the name in the database.
2780 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2781 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2782 // Get the new folder icon `Bitmap`.
2783 Bitmap folderIconBitmap;
2784 if (defaultFolderIconRadioButton.isChecked()) {
2785 // Get the default folder icon and convert it to a `Bitmap`.
2786 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2787 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2788 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2789 } else { // Use the `WebView` favorite icon.
2790 folderIconBitmap = favoriteIconBitmap;
2793 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2794 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2795 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2796 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2798 // Update the folder icon in the database.
2799 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2800 } else { // The folder icon and the name have changed.
2801 // Get the new folder icon `Bitmap`.
2802 Bitmap folderIconBitmap;
2803 if (defaultFolderIconRadioButton.isChecked()) {
2804 // Get the default folder icon and convert it to a `Bitmap`.
2805 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2806 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2807 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2808 } else { // Use the `WebView` favorite icon.
2809 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2812 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2813 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2814 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2815 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2817 // Update the folder name and icon in the database.
2818 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2821 // Update `bookmarksCursor` with the current contents of this folder.
2822 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2824 // Update the `ListView`.
2825 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2829 public void onHttpAuthenticationCancel() {
2830 // Cancel the `HttpAuthHandler`.
2831 httpAuthHandler.cancel();
2835 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2836 // Get handles for the `EditTexts`.
2837 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2838 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2840 // Proceed with the HTTP authentication.
2841 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2844 public void viewSslCertificate(View view) {
2845 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2846 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2847 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2851 public void onSslErrorCancel() {
2852 sslErrorHandler.cancel();
2856 public void onSslErrorProceed() {
2857 sslErrorHandler.proceed();
2861 public void onSslMismatchBack() {
2862 if (mainWebView.canGoBack()) { // There is a back page in the history.
2863 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2864 navigatingHistory = true;
2867 mainWebView.goBack();
2868 } else { // There are no pages to go back to.
2869 // Load a blank page
2875 public void onSslMismatchProceed() {
2876 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2877 ignorePinnedSslCertificate = true;
2881 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2882 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2883 navigatingHistory = true;
2885 // Load the history entry.
2886 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2890 public void onClearHistory() {
2891 // Clear the history.
2892 mainWebView.clearHistory();
2895 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2897 public void onBackPressed() {
2898 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2899 // Close the navigation drawer.
2900 drawerLayout.closeDrawer(GravityCompat.START);
2901 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2902 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2903 // close the bookmarks drawer.
2904 drawerLayout.closeDrawer(GravityCompat.END);
2905 } else { // A subfolder is displayed.
2906 // Place the former parent folder in `currentFolder`.
2907 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2909 // Load the new folder.
2910 loadBookmarksFolder();
2913 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2914 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2915 navigatingHistory = true;
2918 mainWebView.goBack();
2919 } else { // There isn't anything to do in Privacy Browser.
2920 // Pass `onBackPressed()` to the system.
2921 super.onBackPressed();
2925 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2926 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2927 String unformattedUrlString = urlTextBox.getText().toString().trim();
2929 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2930 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2931 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2932 if (!unformattedUrlString.startsWith("http")) {
2933 unformattedUrlString = "http://" + unformattedUrlString;
2936 // Initialize `unformattedUrl`.
2937 URL unformattedUrl = null;
2939 // 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.
2941 unformattedUrl = new URL(unformattedUrlString);
2942 } catch (MalformedURLException e) {
2943 e.printStackTrace();
2946 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2947 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2948 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2949 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2950 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2951 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2954 Uri.Builder formattedUri = new Uri.Builder();
2955 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2957 // Decode `formattedUri` as a `String` in `UTF-8`.
2958 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2960 // Sanitize the search input and convert it to a search.
2961 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2963 // Add the base search URL.
2964 formattedUrlString = searchURL + encodedUrlString;
2967 // 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.
2968 urlTextBox.clearFocus();
2970 loadUrl(formattedUrlString);
2974 private void loadUrl(String url) {
2975 // Apply any custom domain settings.
2976 applyDomainSettings(url, true);
2979 mainWebView.loadUrl(url, customHeaders);
2981 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2982 urlIsLoading = true;
2985 public void findPreviousOnPage(View view) {
2986 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2987 mainWebView.findNext(false);
2990 public void findNextOnPage(View view) {
2991 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2992 mainWebView.findNext(true);
2995 public void closeFindOnPage(View view) {
2996 // Delete the contents of `find_on_page_edittext`.
2997 findOnPageEditText.setText(null);
2999 // Clear the highlighted phrases.
3000 mainWebView.clearMatches();
3002 // Hide the Find on Page `RelativeLayout`.
3003 findOnPageLinearLayout.setVisibility(View.GONE);
3005 // Show the URL app bar.
3006 supportAppBar.setVisibility(View.VISIBLE);
3008 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3009 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3012 private void applyAppSettings() {
3013 // Get a handle for the shared preferences.
3014 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3016 // Store the values from the shared preferences in variables.
3017 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3018 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3019 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3020 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3021 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3022 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3023 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3024 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3025 fanboyAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3026 fanboySocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3027 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3028 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3029 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3030 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3031 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3032 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3033 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
3034 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3036 // Set the homepage, search, and proxy options.
3037 if (proxyThroughOrbot) { // Set the Tor options.
3038 // Set `torHomepageString` as `homepage`.
3039 homepage = torHomepageString;
3041 // If formattedUrlString is null assign the homepage to it.
3042 if (formattedUrlString == null) {
3043 formattedUrlString = homepage;
3046 // Set the search URL.
3047 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3048 searchURL = torSearchCustomURLString;
3049 } else { // Use the string from the pre-built list.
3050 searchURL = torSearchString;
3053 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3054 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3056 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3058 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3060 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3063 // Display a message to the user if we are waiting on Orbot.
3064 if (!orbotStatus.equals("ON")) {
3065 // Set `waitingForOrbot`.
3066 waitingForOrbot = true;
3068 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3069 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3071 } else { // Set the non-Tor options.
3072 // Set `homepageString` as `homepage`.
3073 homepage = homepageString;
3075 // If formattedUrlString is null assign the homepage to it.
3076 if (formattedUrlString == null) {
3077 formattedUrlString = homepage;
3080 // Set the search URL.
3081 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3082 searchURL = searchCustomURLString;
3083 } else { // Use the string from the pre-built list.
3084 searchURL = searchString;
3087 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3088 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3090 // Set the default `appBar` background. `this` refers to the context.
3092 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3094 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3097 // Reset `waitingForOrbot.
3098 waitingForOrbot = false;
3101 // Set swipe to refresh.
3102 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
3104 // Set Do Not Track status.
3105 if (doNotTrackEnabled) {
3106 customHeaders.put("DNT", "1");
3108 customHeaders.remove("DNT");
3111 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3112 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3113 if (hideSystemBarsOnFullscreen) { // Hide everything.
3114 // Remove the translucent navigation setting if it is currently flagged.
3115 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3117 // Remove the translucent status bar overlay.
3118 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3120 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3121 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3123 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3124 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3125 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3127 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3128 } else { // Hide everything except the status and navigation bars.
3129 // Add the translucent status flag if it is unset.
3130 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3132 if (translucentNavigationBarOnFullscreen) {
3133 // Set the navigation bar to be translucent.
3134 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3136 // Set the navigation bar to be black.
3137 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3140 } else { // Switch to normal viewing mode.
3141 // Reset `inFullScreenBrowsingMode` to `false`.
3142 inFullScreenBrowsingMode = false;
3144 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3145 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3149 // Show the `BannerAd` in the free flavor.
3150 if (BuildConfig.FLAVOR.contentEquals("free")) {
3151 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
3152 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
3154 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3155 adView = findViewById(R.id.adview);
3158 // Remove the translucent navigation bar flag if it is set.
3159 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3161 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3162 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3164 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3165 rootCoordinatorLayout.setSystemUiVisibility(0);
3167 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3168 rootCoordinatorLayout.setFitsSystemWindows(true);
3173 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3174 @SuppressWarnings("deprecation")
3175 private void applyDomainSettings(String url, boolean resetFavoriteIcon) {
3176 // Reset `navigatingHistory`.
3177 navigatingHistory = false;
3179 // Parse the URL into a URI.
3180 Uri uri = Uri.parse(url);
3182 // Extract the domain from `uri`.
3183 String hostName = uri.getHost();
3185 // Initialize `loadingNewDomainName`.
3186 boolean loadingNewDomainName;
3188 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3189 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3190 //noinspection SimplifiableIfStatement
3191 if ((hostName == null) || (currentDomainName == null)) {
3192 loadingNewDomainName = true;
3193 } else { // Determine if `hostName` equals `currentDomainName`.
3194 loadingNewDomainName = !hostName.equals(currentDomainName);
3197 // 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.
3198 if (loadingNewDomainName) {
3199 // Set the new `hostname` as the `currentDomainName`.
3200 currentDomainName = hostName;
3202 // Reset `ignorePinnedSslCertificate`.
3203 ignorePinnedSslCertificate = false;
3205 // Reset the favorite icon if specified.
3206 if (resetFavoriteIcon) {
3207 favoriteIconBitmap = favoriteIconDefaultBitmap;
3208 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3211 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3212 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3213 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3215 // Get a full cursor from `domainsDatabaseHelper`.
3216 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3218 // Initialize `domainSettingsSet`.
3219 Set<String> domainSettingsSet = new HashSet<>();
3221 // Get the domain name column index.
3222 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3224 // Populate `domainSettingsSet`.
3225 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3226 // Move `domainsCursor` to the current row.
3227 domainNameCursor.moveToPosition(i);
3229 // Store the domain name in `domainSettingsSet`.
3230 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3233 // Close `domainNameCursor.
3234 domainNameCursor.close();
3236 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3237 domainSettingsApplied = false;
3238 String domainNameInDatabase = null;
3240 // Check the hostname.
3241 if (domainSettingsSet.contains(hostName)) {
3242 domainSettingsApplied = true;
3243 domainNameInDatabase = hostName;
3246 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3247 if (hostName != null) {
3248 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3249 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3250 domainSettingsApplied = true;
3251 domainNameInDatabase = "*." + hostName;
3254 // Strip out the lowest subdomain of `host`.
3255 hostName = hostName.substring(hostName.indexOf(".") + 1);
3259 // Get a handle for the shared preference. `this` references the current context.
3260 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3262 // Store the general preference information.
3263 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3264 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3265 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3266 nightMode = sharedPreferences.getBoolean("night_mode", false);
3268 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3269 // Get a cursor for the current host and move it to the first position.
3270 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3271 currentHostDomainSettingsCursor.moveToFirst();
3273 // Get the settings from the cursor.
3274 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3275 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3276 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3277 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3278 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3279 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3280 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3281 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3282 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3283 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3284 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3285 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3286 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3287 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3288 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3289 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3290 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3292 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3293 switch (nightModeInt) {
3294 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3298 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3303 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3305 javaScriptEnabled = true;
3308 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3309 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3310 pinnedDomainSslStartDate = null;
3312 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3315 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3316 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3317 pinnedDomainSslEndDate = null;
3319 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3322 // Close `currentHostDomainSettingsCursor`.
3323 currentHostDomainSettingsCursor.close();
3325 // Apply the domain settings.
3326 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3327 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3328 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3329 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3331 // Apply the font size.
3332 if (fontSize == 0) { // Apply the default font size.
3333 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3334 } else { // Apply the specified font size.
3335 mainWebView.getSettings().setTextZoom(fontSize);
3338 // Set third-party cookies status if API >= 21.
3339 if (Build.VERSION.SDK_INT >= 21) {
3340 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3343 // 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.
3344 // <https://redmine.stoutner.com/issues/160>
3345 if (!urlIsLoading) {
3346 switch (userAgentString) {
3347 case "System default user agent":
3348 // Set the user agent according to the system default.
3349 switch (defaultUserAgentString) {
3350 case "WebView default user agent":
3351 // Set the user agent to `""`, which uses the default value.
3352 mainWebView.getSettings().setUserAgentString("");
3355 case "Custom user agent":
3356 // Set the custom user agent.
3357 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3361 // Use the selected user agent.
3362 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3366 case "WebView default user agent":
3367 // Set the user agent to `""`, which uses the default value.
3368 mainWebView.getSettings().setUserAgentString("");
3372 // Use the selected user agent.
3373 mainWebView.getSettings().setUserAgentString(userAgentString);
3376 // Store the applied user agent string.
3377 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3380 // 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.
3382 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3384 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3386 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3387 // Store the values from `sharedPreferences` in variables.
3388 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3389 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3390 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3391 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3392 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3394 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3396 javaScriptEnabled = true;
3399 // Apply the default settings.
3400 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3401 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3402 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3403 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3404 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3406 // Reset the pinned SSL certificate information.
3407 domainSettingsDatabaseId = -1;
3408 pinnedDomainSslCertificate = false;
3409 pinnedDomainSslIssuedToCNameString = "";
3410 pinnedDomainSslIssuedToONameString = "";
3411 pinnedDomainSslIssuedToUNameString = "";
3412 pinnedDomainSslIssuedByCNameString = "";
3413 pinnedDomainSslIssuedByONameString = "";
3414 pinnedDomainSslIssuedByUNameString = "";
3415 pinnedDomainSslStartDate = null;
3416 pinnedDomainSslEndDate = null;
3418 // Set third-party cookies status if API >= 21.
3419 if (Build.VERSION.SDK_INT >= 21) {
3420 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3423 // 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.
3424 // <https://redmine.stoutner.com/issues/160>
3425 if (!urlIsLoading) {
3426 switch (defaultUserAgentString) {
3427 case "WebView default user agent":
3428 // Set the user agent to `""`, which uses the default value.
3429 mainWebView.getSettings().setUserAgentString("");
3432 case "Custom user agent":
3433 // Set the custom user agent.
3434 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3438 // Use the selected user agent.
3439 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3442 // Store the applied user agent string.
3443 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3446 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3447 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3450 // Close `domainsDatabaseHelper`.
3451 domainsDatabaseHelper.close();
3453 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3454 onTheFlyDisplayImagesSet = false;
3455 setDisplayWebpageImages();
3457 // Update the privacy icons, but only if `mainMenu` has already been populated.
3458 if (mainMenu != null) {
3459 updatePrivacyIcons(true);
3464 private void setDisplayWebpageImages() {
3465 if (!onTheFlyDisplayImagesSet) {
3466 if (domainSettingsApplied) { // Custom domain settings are applied.
3467 switch (displayWebpageImagesInt) {
3468 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3469 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3472 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3473 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3476 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3477 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3480 } else { // Default settings are applied.
3481 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3486 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3487 // Get handles for the icons.
3488 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3489 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3490 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3491 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3493 // Update `privacyIcon`.
3494 if (javaScriptEnabled) { // JavaScript is enabled.
3495 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3496 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3497 privacyIconMenuItem.setIcon(R.drawable.warning);
3498 } else { // All the dangerous features are disabled.
3499 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3502 // Update `firstPartyCookiesIcon`.
3503 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3504 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3505 } else { // First-party cookies are disabled.
3507 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3509 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3513 // Update `domStorageIcon`.
3514 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3515 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3516 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3518 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3520 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3522 } else { // JavaScript is disabled, so DOM storage is ghosted.
3524 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3526 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3530 // Update `formDataIcon`.
3531 if (saveFormDataEnabled) { // Form data is enabled.
3532 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3533 } else { // Form data is disabled.
3535 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3537 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3541 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3542 if (runInvalidateOptionsMenu) {
3543 invalidateOptionsMenu();
3547 private void highlightUrlText() {
3548 String urlString = urlTextBox.getText().toString();
3550 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3551 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3552 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3553 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3556 // Get the index of the `/` immediately after the domain name.
3557 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3559 // De-emphasize the text after the domain name.
3560 if (endOfDomainName > 0) {
3561 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3565 private void loadBookmarksFolder() {
3566 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3567 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3569 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3570 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3572 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3573 // Inflate the individual item layout. `false` does not attach it to the root.
3574 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3578 public void bindView(View view, Context context, Cursor cursor) {
3579 // Get handles for the views.
3580 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3581 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3583 // Get the favorite icon byte array from the `Cursor`.
3584 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3586 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3587 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3589 // Display the bitmap in `bookmarkFavoriteIcon`.
3590 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3592 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3593 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3594 bookmarkNameTextView.setText(bookmarkNameString);
3596 // Make the font bold for folders.
3597 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3598 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3599 } else { // Reset the font to default for normal bookmarks.
3600 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3605 // Populate the `ListView` with the adapter.
3606 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3608 // Set the bookmarks drawer title.
3609 if (currentBookmarksFolder.isEmpty()) {
3610 bookmarksTitleTextView.setText(R.string.bookmarks);
3612 bookmarksTitleTextView.setText(currentBookmarksFolder);