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.Activity;
27 import android.app.DialogFragment;
28 import android.app.DownloadManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.Environment;
51 import android.os.Handler;
52 import android.preference.PreferenceManager;
53 import android.print.PrintDocumentAdapter;
54 import android.print.PrintManager;
55 import android.support.annotation.NonNull;
56 import android.support.design.widget.CoordinatorLayout;
57 import android.support.design.widget.FloatingActionButton;
58 import android.support.design.widget.NavigationView;
59 import android.support.design.widget.Snackbar;
60 import android.support.v4.app.ActivityCompat;
61 import android.support.v4.content.ContextCompat;
62 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
63 import android.support.v4.content.pm.ShortcutInfoCompat;
64 import android.support.v4.content.pm.ShortcutManagerCompat;
65 import android.support.v4.graphics.drawable.IconCompat;
66 import android.support.v4.view.GravityCompat;
67 import android.support.v4.widget.DrawerLayout;
68 import android.support.v4.widget.SwipeRefreshLayout;
69 import android.support.v7.app.ActionBar;
70 import android.support.v7.app.ActionBarDrawerToggle;
71 import android.support.v7.app.AppCompatActivity;
72 import android.support.v7.app.AppCompatDialogFragment;
73 import android.support.v7.widget.Toolbar;
74 import android.text.Editable;
75 import android.text.Spanned;
76 import android.text.TextWatcher;
77 import android.text.style.ForegroundColorSpan;
78 import android.util.Patterns;
79 import android.view.ContextMenu;
80 import android.view.GestureDetector;
81 import android.view.KeyEvent;
82 import android.view.Menu;
83 import android.view.MenuItem;
84 import android.view.MotionEvent;
85 import android.view.View;
86 import android.view.ViewGroup;
87 import android.view.WindowManager;
88 import android.view.inputmethod.InputMethodManager;
89 import android.webkit.CookieManager;
90 import android.webkit.HttpAuthHandler;
91 import android.webkit.SslErrorHandler;
92 import android.webkit.ValueCallback;
93 import android.webkit.WebBackForwardList;
94 import android.webkit.WebChromeClient;
95 import android.webkit.WebResourceResponse;
96 import android.webkit.WebStorage;
97 import android.webkit.WebView;
98 import android.webkit.WebViewClient;
99 import android.webkit.WebViewDatabase;
100 import android.widget.ArrayAdapter;
101 import android.widget.CursorAdapter;
102 import android.widget.EditText;
103 import android.widget.FrameLayout;
104 import android.widget.ImageView;
105 import android.widget.LinearLayout;
106 import android.widget.ListView;
107 import android.widget.ProgressBar;
108 import android.widget.RadioButton;
109 import android.widget.RelativeLayout;
110 import android.widget.TextView;
112 import com.stoutner.privacybrowser.BuildConfig;
113 import com.stoutner.privacybrowser.R;
114 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
116 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
117 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
118 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
119 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
120 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
121 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
122 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
123 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
124 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
125 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
126 import com.stoutner.privacybrowser.helpers.AdHelper;
127 import com.stoutner.privacybrowser.helpers.BlockListHelper;
128 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
129 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
130 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
131 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
132 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
134 import java.io.ByteArrayInputStream;
135 import java.io.ByteArrayOutputStream;
137 import java.io.IOException;
138 import java.io.UnsupportedEncodingException;
139 import java.net.MalformedURLException;
141 import java.net.URLDecoder;
142 import java.net.URLEncoder;
143 import java.util.ArrayList;
144 import java.util.Date;
145 import java.util.HashMap;
146 import java.util.HashSet;
147 import java.util.List;
148 import java.util.Map;
149 import java.util.Set;
151 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
152 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
153 CreateHomeScreenShortcutDialog.CreateHomeScreenShortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
154 DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
155 HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
156 SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
158 // `darkTheme` is public static so it can be accessed from everywhere.
159 public static boolean darkTheme;
161 // `allowScreenshots` is public static so it can be accessed from everywhere. It is also used in `onCreate()`.
162 public static boolean allowScreenshots;
164 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
165 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
166 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
167 public static Bitmap favoriteIconBitmap;
169 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
170 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, `loadUrlFromTextBox()`, and `applyProxyThroughOrbot()`.
171 public static String formattedUrlString;
173 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
174 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
175 public static SslCertificate sslCertificate;
177 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
178 public static String orbotStatus;
180 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
181 public static String webViewTitle;
183 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
184 public static String appliedUserAgentString;
186 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
187 public static boolean reloadOnRestart;
189 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`. It is also used in `onRestart()`.
190 public static boolean loadUrlOnRestart;
192 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
193 public static boolean restartFromBookmarksActivity;
195 // The block list versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
196 public static String easyListVersion;
197 public static String easyPrivacyVersion;
198 public static String fanboysAnnoyanceVersion;
199 public static String fanboysSocialVersion;
200 public static String ultraPrivacyVersion;
202 // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`. They are also used in `onCreate()` and `onPrepareOptionsMenu()`.
203 public static List<String[]> resourceRequests;
204 public static String[] whiteListResultStringArray;
205 private int blockedRequests;
206 private int easyListBlockedRequests;
207 private int easyPrivacyBlockedRequests;
208 private int fanboysAnnoyanceListBlockedRequests;
209 private int fanboysSocialBlockingListBlockedRequests;
210 private int ultraPrivacyBlockedRequests;
211 private int thirdPartyBlockedRequests;
213 public final static int REQUEST_DISPOSITION = 0;
214 public final static int REQUEST_URL = 1;
215 public final static int REQUEST_BLOCKLIST = 2;
216 public final static int REQUEST_SUBLIST = 3;
217 public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
218 public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
220 public final static int REQUEST_DEFAULT = 0;
221 public final static int REQUEST_ALLOWED = 1;
222 public final static int REQUEST_THIRD_PARTY = 2;
223 public final static int REQUEST_BLOCKED = 3;
225 public final static int MAIN_WHITELIST = 1;
226 public final static int FINAL_WHITELIST = 2;
227 public final static int DOMAIN_WHITELIST = 3;
228 public final static int DOMAIN_INITIAL_WHITELIST = 4;
229 public final static int DOMAIN_FINAL_WHITELIST = 5;
230 public final static int THIRD_PARTY_WHITELIST = 6;
231 public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
232 public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
234 public final static int MAIN_BLACKLIST = 9;
235 public final static int INITIAL_BLACKLIST = 10;
236 public final static int FINAL_BLACKLIST = 11;
237 public final static int DOMAIN_BLACKLIST = 12;
238 public final static int DOMAIN_INITIAL_BLACKLIST = 13;
239 public final static int DOMAIN_FINAL_BLACKLIST = 14;
240 public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
241 public final static int THIRD_PARTY_BLACKLIST = 16;
242 public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
243 public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
244 public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
245 public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
246 public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
247 public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
249 // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
250 // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
251 public static boolean blockAllThirdPartyRequests;
253 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
254 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
255 public static String currentBookmarksFolder;
257 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
258 public static int domainSettingsDatabaseId;
260 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
261 public static String pinnedDomainSslIssuedToCNameString;
262 public static String pinnedDomainSslIssuedToONameString;
263 public static String pinnedDomainSslIssuedToUNameString;
264 public static String pinnedDomainSslIssuedByCNameString;
265 public static String pinnedDomainSslIssuedByONameString;
266 public static String pinnedDomainSslIssuedByUNameString;
267 public static Date pinnedDomainSslStartDate;
268 public static Date pinnedDomainSslEndDate;
270 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
271 public final static int UNRECOGNIZED_USER_AGENT = -1;
272 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
273 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
274 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
275 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
276 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
279 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
280 private ActionBar appBar;
282 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
283 private boolean navigatingHistory;
285 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
286 private Bitmap favoriteIconDefaultBitmap;
288 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
289 private DrawerLayout drawerLayout;
291 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
292 private CoordinatorLayout rootCoordinatorLayout;
294 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
295 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `applyProxyThroughOrbot()`.
296 private WebView mainWebView;
298 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
299 private FrameLayout fullScreenVideoFrameLayout;
301 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
302 private SwipeRefreshLayout swipeRefreshLayout;
304 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
305 private RelativeLayout urlAppBarRelativeLayout;
307 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
308 private ImageView favoriteIconImageView;
310 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
311 private CookieManager cookieManager;
313 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
314 private final Map<String, String> customHeaders = new HashMap<>();
316 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
317 private boolean javaScriptEnabled;
319 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
320 private boolean firstPartyCookiesEnabled;
322 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
323 private boolean thirdPartyCookiesEnabled;
325 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
326 private boolean domStorageEnabled;
328 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`. It can be removed once the minimum API >= 26.
329 private boolean saveFormDataEnabled;
331 // `nightMode` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
332 private boolean nightMode;
334 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyProxyThroughOrbot()`.
335 private String homepage;
337 // `searchURL` is used in `loadURLFromTextBox()` and `applyProxyThroughOrbot()`.
338 private String searchURL;
340 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
341 private Menu mainMenu;
343 // `refreshMenuItem` is used in `onCreate()` and `onCreateOptionsMenu()`.
344 private MenuItem refreshMenuItem;
346 // The blocklist menu items are used in `onCreate()`, `onCreateOptionsMenu()`, and `onPrepareOptionsMenu()`.
347 private MenuItem blocklistsMenuItem;
348 private MenuItem easyListMenuItem;
349 private MenuItem easyPrivacyMenuItem;
350 private MenuItem fanboysAnnoyanceListMenuItem;
351 private MenuItem fanboysSocialBlockingListMenuItem;
352 private MenuItem ultraPrivacyMenuItem;
353 private MenuItem blockAllThirdPartyRequestsMenuItem;
355 // The blocklist variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
356 private boolean easyListEnabled;
357 private boolean easyPrivacyEnabled;
358 private boolean fanboysAnnoyanceListEnabled;
359 private boolean fanboysSocialBlockingListEnabled;
360 private boolean ultraPrivacyEnabled;
362 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
363 private String webViewDefaultUserAgent;
365 // `defaultCustomUserAgentString` is used in `onPrepareOptionsMenu()` and `applyDomainSettings()`.
366 private String defaultCustomUserAgentString;
368 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
369 private Runtime privacyBrowserRuntime;
371 // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
372 private boolean proxyThroughOrbot;
374 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
375 private boolean incognitoModeEnabled;
377 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
378 private boolean fullScreenBrowsingModeEnabled;
380 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
381 private boolean inFullScreenBrowsingMode;
383 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
384 private boolean hideSystemBarsOnFullscreen;
386 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
387 private boolean translucentNavigationBarOnFullscreen;
389 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
390 private boolean reapplyDomainSettingsOnRestart;
392 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
393 private boolean reapplyAppSettingsOnRestart;
395 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
396 private boolean displayingFullScreenVideo;
398 // `downloadWithExternalApp` is used in `onCreate()`, `onCreateContextMenu()`, and `applyDomainSettings()`.
399 private boolean downloadWithExternalApp;
401 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
402 private String currentDomainName;
404 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
405 private boolean ignorePinnedSslCertificate;
407 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
408 private BroadcastReceiver orbotStatusBroadcastReceiver;
410 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
411 private boolean waitingForOrbot;
413 // `domainSettingsApplied` is used in `prepareOptionsMenu()` and `applyDomainSettings()`.
414 private boolean domainSettingsApplied;
416 // `domainSettingsJavaScriptEnabled` is used in `onOptionsItemSelected()` and `applyDomainSettings()`.
417 private Boolean domainSettingsJavaScriptEnabled;
419 // `waitingForOrbotHtmlString` is used in `onCreate()` and `applyProxyThroughOrbot()`.
420 private String waitingForOrbotHtmlString;
422 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
423 private String privateDataDirectoryString;
425 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
426 private LinearLayout findOnPageLinearLayout;
428 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
429 private EditText findOnPageEditText;
431 // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
432 private boolean displayAdditionalAppBarIcons;
434 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
435 private ActionBarDrawerToggle drawerToggle;
437 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
438 private Toolbar supportAppBar;
440 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
441 private EditText urlTextBox;
443 // The color spans are used in `onCreate()` and `highlightUrlText()`.
444 private ForegroundColorSpan redColorSpan;
445 private ForegroundColorSpan initialGrayColorSpan;
446 private ForegroundColorSpan finalGrayColorSpan;
448 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
449 private SslErrorHandler sslErrorHandler;
451 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
452 private static HttpAuthHandler httpAuthHandler;
454 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
455 private InputMethodManager inputMethodManager;
457 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
458 private RelativeLayout mainWebViewRelativeLayout;
460 // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
461 private boolean urlIsLoading;
463 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
464 private boolean pinnedDomainSslCertificate;
466 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
467 // and `loadBookmarksFolder()`.
468 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
470 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
471 private ListView bookmarksListView;
473 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
474 private TextView bookmarksTitleTextView;
476 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
477 private Cursor bookmarksCursor;
479 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
480 private CursorAdapter bookmarksCursorAdapter;
482 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
483 private String oldFolderNameString;
485 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
486 private ValueCallback<Uri[]> fileChooserCallback;
488 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
489 private String downloadUrl;
490 private String downloadContentDisposition;
491 private long downloadContentLength;
493 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
494 private String downloadImageUrl;
496 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
497 private ArrayAdapter<CharSequence> userAgentNamesArray;
498 private String[] userAgentDataArray;
500 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
501 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
502 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
505 // 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.
506 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
507 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
508 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
509 @SuppressWarnings("deprecation")
510 protected void onCreate(Bundle savedInstanceState) {
511 // Get a handle for the shared preferences.
512 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
514 // Get the theme and screenshot preferences.
515 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
516 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
518 // Disable screenshots if not allowed.
519 if (!allowScreenshots) {
520 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
523 // Set the activity theme.
525 setTheme(R.style.PrivacyBrowserDark);
527 setTheme(R.style.PrivacyBrowserLight);
530 // Run the default commands.
531 super.onCreate(savedInstanceState);
533 // Set the content view.
534 setContentView(R.layout.main_drawerlayout);
536 // Get a handle for `inputMethodManager`.
537 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
539 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
540 supportAppBar = findViewById(R.id.app_bar);
541 setSupportActionBar(supportAppBar);
542 appBar = getSupportActionBar();
544 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
545 assert appBar != null;
547 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
548 appBar.setCustomView(R.layout.url_app_bar);
549 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
551 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
552 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
553 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
554 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
556 // Get a handle for `urlTextBox`.
557 urlTextBox = findViewById(R.id.url_edittext);
559 // Remove the formatting from `urlTextBar` when the user is editing the text.
560 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
561 if (hasFocus) { // The user is editing the URL text box.
562 // Remove the highlighting.
563 urlTextBox.getText().removeSpan(redColorSpan);
564 urlTextBox.getText().removeSpan(initialGrayColorSpan);
565 urlTextBox.getText().removeSpan(finalGrayColorSpan);
566 } else { // The user has stopped editing the URL text box.
567 // Move to the beginning of the string.
568 urlTextBox.setSelection(0);
570 // Reapply the highlighting.
575 // Set the go button on the keyboard to load the URL in `urlTextBox`.
576 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
577 // If the event is a key-down event on the `enter` button, load the URL.
578 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
579 // Load the URL into the mainWebView and consume the event.
581 loadUrlFromTextBox();
582 } catch (UnsupportedEncodingException e) {
585 // If the enter key was pressed, consume the event.
588 // If any other key was pressed, do not consume the event.
593 // Set `waitingForOrbotHTMLString`.
594 waitingForOrbotHtmlString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
596 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
597 currentDomainName = "";
598 orbotStatus = "unknown";
599 waitingForOrbot = false;
601 // Create an Orbot status `BroadcastReceiver`.
602 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
604 public void onReceive(Context context, Intent intent) {
605 // Store the content of the status message in `orbotStatus`.
606 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
608 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
609 if (orbotStatus.equals("ON") && waitingForOrbot) {
610 // Reset `waitingForOrbot`.
611 waitingForOrbot = false;
613 // Load `formattedUrlString
614 loadUrl(formattedUrlString);
619 // Register `orbotStatusBroadcastReceiver` on `this` context.
620 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
622 // Get handles for views that need to be accessed.
623 drawerLayout = findViewById(R.id.drawerlayout);
624 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
625 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
626 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
627 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
628 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
629 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
630 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
631 mainWebView = findViewById(R.id.main_webview);
632 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
633 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
634 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
635 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
636 favoriteIconImageView = findViewById(R.id.favorite_icon);
638 // 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.
640 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
641 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
642 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
643 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
645 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
646 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
647 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
648 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
651 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
652 launchBookmarksActivityFab.setOnClickListener(v -> {
653 // Create an intent to launch the bookmarks activity.
654 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
656 // Include the current folder with the `Intent`.
657 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
660 startActivity(bookmarksIntent);
663 // Set the create new bookmark folder FAB to display an alert dialog.
664 createBookmarkFolderFab.setOnClickListener(v -> {
665 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
666 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
667 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
670 // Set the create new bookmark FAB to display an alert dialog.
671 createBookmarkFab.setOnClickListener(view -> {
672 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
673 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
674 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
677 // Create a double-tap listener to toggle full-screen mode.
678 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
679 // Override `onDoubleTap()`. All other events are handled using the default settings.
681 public boolean onDoubleTap(MotionEvent event) {
682 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
683 // Toggle `inFullScreenBrowsingMode`.
684 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
686 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
687 // Hide the `appBar`.
690 // Hide the banner ad in the free flavor.
691 if (BuildConfig.FLAVOR.contentEquals("free")) {
692 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
693 AdHelper.hideAd(findViewById(R.id.adview));
696 // Modify the system bars.
697 if (hideSystemBarsOnFullscreen) { // Hide everything.
698 // Remove the translucent overlays.
699 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
701 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
702 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
704 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
705 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
706 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
708 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
710 // Set `rootCoordinatorLayout` to fill the whole screen.
711 rootCoordinatorLayout.setFitsSystemWindows(false);
712 } else { // Hide everything except the status and navigation bars.
713 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
714 rootCoordinatorLayout.setFitsSystemWindows(false);
716 // 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.
717 if (translucentNavigationBarOnFullscreen) {
718 // Set the navigation bar to be translucent.
719 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
722 } else { // Switch to normal viewing mode.
723 // Show the `appBar`.
726 // Show the `BannerAd` in the free flavor.
727 if (BuildConfig.FLAVOR.contentEquals("free")) {
728 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
729 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
732 // Remove the translucent navigation bar flag if it is set.
733 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
735 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
736 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
738 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
739 rootCoordinatorLayout.setSystemUiVisibility(0);
741 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
742 rootCoordinatorLayout.setFitsSystemWindows(true);
745 // Consume the double-tap.
747 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
753 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
754 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
755 // Call `performClick()` on the view, which is required for accessibility.
758 // Send the `event` to `gestureDetector`.
759 return gestureDetector.onTouchEvent(event);
762 // Update `findOnPageCountTextView`.
763 mainWebView.setFindListener(new WebView.FindListener() {
764 // Get a handle for `findOnPageCountTextView`.
765 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
768 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
769 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
770 // Set `findOnPageCountTextView` to `0/0`.
771 findOnPageCountTextView.setText(R.string.zero_of_zero);
772 } else if (isDoneCounting) { // There are matches.
773 // `activeMatchOrdinal` is zero-based.
774 int activeMatch = activeMatchOrdinal + 1;
776 // Build the match string.
777 String matchString = activeMatch + "/" + numberOfMatches;
779 // Set `findOnPageCountTextView`.
780 findOnPageCountTextView.setText(matchString);
785 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
786 findOnPageEditText.addTextChangedListener(new TextWatcher() {
788 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
793 public void onTextChanged(CharSequence s, int start, int before, int count) {
798 public void afterTextChanged(Editable s) {
799 // Search for the text in `mainWebView`.
800 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
804 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
805 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
806 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
807 // Hide the soft keyboard. `0` indicates no additional flags.
808 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
810 // Consume the event.
812 } else { // A different key was pressed.
813 // Do not consume the event.
818 // Implement swipe to refresh
819 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
820 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
821 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
823 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
824 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
825 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
827 // Listen for touches on the navigation menu.
828 final NavigationView navigationView = findViewById(R.id.navigationview);
829 navigationView.setNavigationItemSelectedListener(this);
831 // 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.
832 final Menu navigationMenu = navigationView.getMenu();
833 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
834 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
835 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
836 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
838 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
839 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
840 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
842 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
843 currentBookmarksFolder = "";
845 // Load the home folder, which is `""` in the database.
846 loadBookmarksFolder();
848 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
849 // Convert the id from long to int to match the format of the bookmarks database.
850 int databaseID = (int) id;
852 // Get the bookmark cursor for this ID and move it to the first row.
853 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
854 bookmarkCursor.moveToFirst();
856 // Act upon the bookmark according to the type.
857 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
858 // Store the new folder name in `currentBookmarksFolder`.
859 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
861 // Load the new folder.
862 loadBookmarksFolder();
863 } else { // The selected bookmark is not a folder.
864 // Load the bookmark URL.
865 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
867 // Close the bookmarks drawer.
868 drawerLayout.closeDrawer(GravityCompat.END);
871 // Close the `Cursor`.
872 bookmarkCursor.close();
875 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
876 // Convert the database ID from `long` to `int`.
877 int databaseId = (int) id;
879 // Find out if the selected bookmark is a folder.
880 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
883 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
884 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
886 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
887 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
888 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
890 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
891 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
892 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
895 // Consume the event.
899 // The drawer listener is used to update the navigation menu.
900 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
902 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
906 public void onDrawerOpened(@NonNull View drawerView) {
910 public void onDrawerClosed(@NonNull View drawerView) {
914 public void onDrawerStateChanged(int newState) {
915 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
916 // Update the back, forward, history, and requests menu items.
917 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
918 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
919 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
920 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
922 // Hide the keyboard (if displayed).
923 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
925 // Clear the focus from from the URL text box.
926 urlTextBox.clearFocus();
931 // drawerToggle creates the hamburger icon at the start of the AppBar.
932 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
934 // Get a handle for the progress bar.
935 final ProgressBar progressBar = findViewById(R.id.progress_bar);
937 mainWebView.setWebChromeClient(new WebChromeClient() {
938 // Update the progress bar when a page is loading.
940 public void onProgressChanged(WebView view, int progress) {
941 // Inject the night mode CSS if night mode is enabled.
943 // `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
944 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
945 // `border: none` removes all borders, which can also be used to underline text.
946 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
947 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
948 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
949 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
950 // Initialize a handler to display `mainWebView`.
951 Handler displayWebViewHandler = new Handler();
953 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
954 Runnable displayWebViewRunnable = () -> {
955 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
956 if (progressBar.getVisibility() == View.GONE) {
957 mainWebView.setVisibility(View.VISIBLE);
961 // Displaying of `mainWebView` after 500 milliseconds.
962 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
966 // Update the progress bar.
967 progressBar.setProgress(progress);
969 // Set the visibility of the progress bar.
970 if (progress < 100) {
971 // Show the progress bar.
972 progressBar.setVisibility(View.VISIBLE);
974 // Hide the progress bar.
975 progressBar.setVisibility(View.GONE);
977 // Display `mainWebView` if night mode is disabled.
978 // 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
979 // currently enabled.
981 mainWebView.setVisibility(View.VISIBLE);
984 //Stop the swipe to refresh indicator if it is running
985 swipeRefreshLayout.setRefreshing(false);
989 // Set the favorite icon when it changes.
991 public void onReceivedIcon(WebView view, Bitmap icon) {
992 // Only update the favorite icon if the website has finished loading.
993 if (progressBar.getVisibility() == View.GONE) {
994 // Save a copy of the favorite icon.
995 favoriteIconBitmap = icon;
997 // Place the favorite icon in the appBar.
998 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1002 // Save a copy of the title when it changes.
1004 public void onReceivedTitle(WebView view, String title) {
1005 // Save a copy of the title.
1006 webViewTitle = title;
1009 // Enter full screen video.
1011 public void onShowCustomView(View view, CustomViewCallback callback) {
1012 // Set the full screen video flag.
1013 displayingFullScreenVideo = true;
1015 // Pause the ad if this is the free flavor.
1016 if (BuildConfig.FLAVOR.contentEquals("free")) {
1017 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1018 AdHelper.pauseAd(findViewById(R.id.adview));
1021 // Remove the translucent overlays.
1022 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1024 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1025 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1027 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1028 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1029 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1031 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1033 // Set `rootCoordinatorLayout` to fill the entire screen.
1034 rootCoordinatorLayout.setFitsSystemWindows(false);
1036 // Disable the sliding drawers.
1037 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1039 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1040 fullScreenVideoFrameLayout.addView(view);
1041 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1044 // Exit full screen video.
1046 public void onHideCustomView() {
1047 // Unset the full screen video flag.
1048 displayingFullScreenVideo = false;
1050 // Hide `fullScreenVideoFrameLayout`.
1051 fullScreenVideoFrameLayout.removeAllViews();
1052 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1054 // Enable the sliding drawers.
1055 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1057 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1058 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1059 if (hideSystemBarsOnFullscreen) { // Hide everything.
1060 // Remove the translucent navigation setting if it is currently flagged.
1061 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1063 // Remove the translucent status bar overlay.
1064 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1066 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1067 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1069 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1070 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1071 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1073 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1074 } else { // Hide everything except the status and navigation bars.
1075 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1076 rootCoordinatorLayout.setSystemUiVisibility(0);
1078 // Add the translucent status flag if it is unset.
1079 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1081 if (translucentNavigationBarOnFullscreen) {
1082 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1083 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1085 // Set the navigation bar to be black.
1086 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1089 } else { // Switch to normal viewing mode.
1090 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1091 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1095 // Show the `BannerAd` in the free flavor.
1096 if (BuildConfig.FLAVOR.contentEquals("free")) {
1097 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1098 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
1101 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1102 rootCoordinatorLayout.setSystemUiVisibility(0);
1104 // Remove the translucent navigation bar flag if it is set.
1105 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1107 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1108 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1110 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1111 rootCoordinatorLayout.setFitsSystemWindows(true);
1114 // Show the ad if this is the free flavor.
1115 if (BuildConfig.FLAVOR.contentEquals("free")) {
1116 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1117 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
1123 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1124 // Show the file chooser if the device is running API >= 21.
1125 if (Build.VERSION.SDK_INT >= 21) {
1126 // Store the file path callback.
1127 fileChooserCallback = filePathCallback;
1129 // Create an intent to open a chooser based ont the file chooser parameters.
1130 Intent fileChooserIntent = fileChooserParams.createIntent();
1132 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1133 startActivityForResult(fileChooserIntent, 0);
1139 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1140 registerForContextMenu(mainWebView);
1142 // Allow the downloading of files.
1143 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1144 // Check if the download should be processed by an external app.
1145 if (downloadWithExternalApp) { // Download with an external app.
1146 openUrlWithExternalApp(url);
1147 } else { // Download with Android's download manager.
1148 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1149 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
1150 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1152 // Store the variables for future use by `onRequestPermissionsResult()`.
1154 downloadContentDisposition = contentDisposition;
1155 downloadContentLength = contentLength;
1157 // Show a dialog if the user has previously denied the permission.
1158 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1159 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1160 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1162 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1163 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1164 } else { // Show the permission request directly.
1165 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1166 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1168 } else { // The storage permission has already been granted.
1169 // Get a handle for the download file alert dialog.
1170 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1172 // Show the download file alert dialog.
1173 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1178 // Allow pinch to zoom.
1179 mainWebView.getSettings().setBuiltInZoomControls(true);
1181 // Hide zoom controls.
1182 mainWebView.getSettings().setDisplayZoomControls(false);
1184 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1185 mainWebView.getSettings().setUseWideViewPort(true);
1187 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1188 mainWebView.getSettings().setLoadWithOverviewMode(true);
1190 // Explicitly disable geolocation.
1191 mainWebView.getSettings().setGeolocationEnabled(false);
1193 // Initialize cookieManager.
1194 cookieManager = CookieManager.getInstance();
1196 // 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).
1197 customHeaders.put("X-Requested-With", "");
1199 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1200 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1202 // Get the intent that started the app.
1203 final Intent launchingIntent = getIntent();
1205 // Extract the launching intent data as `launchingIntentUriData`.
1206 final Uri launchingIntentUriData = launchingIntent.getData();
1208 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1209 if (launchingIntentUriData != null) {
1210 formattedUrlString = launchingIntentUriData.toString();
1213 // Get a handle for the `Runtime`.
1214 privacyBrowserRuntime = Runtime.getRuntime();
1216 // Store the application's private data directory.
1217 privateDataDirectoryString = getApplicationInfo().dataDir;
1218 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1220 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1221 inFullScreenBrowsingMode = false;
1223 // Initialize the privacy settings variables.
1224 javaScriptEnabled = false;
1225 firstPartyCookiesEnabled = false;
1226 thirdPartyCookiesEnabled = false;
1227 domStorageEnabled = false;
1228 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1231 // Store the default user agent.
1232 webViewDefaultUserAgent = mainWebView.getSettings().getUserAgentString();
1234 // Initialize the WebView title.
1235 webViewTitle = getString(R.string.no_title);
1237 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1238 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1239 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1240 assert favoriteIconBitmapDrawable != null;
1241 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1243 // If the favorite icon is null, load the default.
1244 if (favoriteIconBitmap == null) {
1245 favoriteIconBitmap = favoriteIconDefaultBitmap;
1248 // Initialize the user agent array adapter and string array.
1249 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
1250 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1252 // Apply the app settings from the shared preferences.
1255 // Instantiate the block list helper.
1256 BlockListHelper blockListHelper = new BlockListHelper();
1258 // Initialize the list of resource requests.
1259 resourceRequests = new ArrayList<>();
1261 // Parse the block lists.
1262 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1263 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1264 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1265 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1266 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1268 // Store the list versions.
1269 easyListVersion = easyList.get(0).get(0)[0];
1270 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1271 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1272 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1273 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1275 // Get a handle for the activity. This is used to update the requests counter while the navigation menu is open.
1276 Activity activity = this;
1278 mainWebView.setWebViewClient(new WebViewClient() {
1279 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1280 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1281 @SuppressWarnings("deprecation")
1283 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1284 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1285 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1286 formattedUrlString = "";
1288 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1289 applyDomainSettings(url, true, false);
1291 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1293 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1294 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1295 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1297 // Parse the url and set it as the data for the intent.
1298 emailIntent.setData(Uri.parse(url));
1300 // Open the email program in a new task instead of as part of Privacy Browser.
1301 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1304 startActivity(emailIntent);
1306 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1308 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1309 // Open the dialer and load the phone number, but wait for the user to place the call.
1310 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1312 // Add the phone number to the intent.
1313 dialIntent.setData(Uri.parse(url));
1315 // Open the dialer in a new task instead of as part of Privacy Browser.
1316 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1319 startActivity(dialIntent);
1321 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1323 } else { // Load a system chooser to select an app that can handle the URL.
1324 // Open an app that can handle the URL.
1325 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1327 // Add the URL to the intent.
1328 genericIntent.setData(Uri.parse(url));
1330 // List all apps that can handle the URL instead of just opening the first one.
1331 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1333 // Open the app in a new task instead of as part of Privacy Browser.
1334 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1336 // Start the app or display a snackbar if no app is available to handle the URL.
1338 startActivity(genericIntent);
1339 } catch (ActivityNotFoundException exception) {
1340 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1343 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1348 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1349 @SuppressWarnings("deprecation")
1351 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1352 // Create an empty web resource response to be used if the resource request is blocked.
1353 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1355 // Reset the whitelist results tracker.
1356 whiteListResultStringArray = null;
1358 // Initialize the third party request tracker.
1359 boolean isThirdPartyRequest = false;
1361 // Initialize the current domain string.
1362 String currentDomain = "";
1364 // Nobody is happy when comparing null strings.
1365 if (!(formattedUrlString == null) && !(url == null)) {
1366 // Get the domain strings to URIs.
1367 Uri currentDomainUri = Uri.parse(formattedUrlString);
1368 Uri requestDomainUri = Uri.parse(url);
1370 // Get the domain host names.
1371 String currentBaseDomain = currentDomainUri.getHost();
1372 String requestBaseDomain = requestDomainUri.getHost();
1374 // Update the current domain variable.
1375 currentDomain = currentBaseDomain;
1377 // Only compare the current base domain and the request base domain if neither is null.
1378 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1379 // Determine the current base domain.
1380 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1381 // Remove the first subdomain.
1382 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1385 // Determine the request base domain.
1386 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1387 // Remove the first subdomain.
1388 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1391 // Update the third party request tracker.
1392 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1396 // Block third-party requests if enabled.
1397 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1398 // Increment the blocked requests counters.
1400 thirdPartyBlockedRequests++;
1402 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1403 activity.runOnUiThread(() -> {
1404 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1405 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1406 blockAllThirdPartyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1409 // Add the request to the log.
1410 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1412 // Return an empty web resource response.
1413 return emptyWebResourceResponse;
1416 // Check UltraPrivacy if it is enabled.
1417 if (ultraPrivacyEnabled) {
1418 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1419 // Increment the blocked requests counters.
1421 ultraPrivacyBlockedRequests++;
1423 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1424 activity.runOnUiThread(() -> {
1425 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1426 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1427 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1430 // The resource request was blocked. Return an empty web resource response.
1431 return emptyWebResourceResponse;
1434 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1435 if (whiteListResultStringArray != null) {
1436 // Add a whitelist entry to the resource requests array.
1437 resourceRequests.add(whiteListResultStringArray);
1439 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1444 // Check EasyList if it is enabled.
1445 if (easyListEnabled) {
1446 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1447 // Increment the blocked requests counters.
1449 easyListBlockedRequests++;
1451 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1452 activity.runOnUiThread(() -> {
1453 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1454 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1455 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1458 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1459 whiteListResultStringArray = null;
1461 // The resource request was blocked. Return an empty web resource response.
1462 return emptyWebResourceResponse;
1466 // Check EasyPrivacy if it is enabled.
1467 if (easyPrivacyEnabled) {
1468 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1469 // Increment the blocked requests counters.
1471 easyPrivacyBlockedRequests++;
1473 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1474 activity.runOnUiThread(() -> {
1475 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1476 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1477 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1480 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1481 whiteListResultStringArray = null;
1483 // The resource request was blocked. Return an empty web resource response.
1484 return emptyWebResourceResponse;
1488 // Check Fanboy’s Annoyance List if it is enabled.
1489 if (fanboysAnnoyanceListEnabled) {
1490 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1491 // Increment the blocked requests counters.
1493 fanboysAnnoyanceListBlockedRequests++;
1495 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1496 activity.runOnUiThread(() -> {
1497 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1498 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1499 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1502 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1503 whiteListResultStringArray = null;
1505 // The resource request was blocked. Return an empty web resource response.
1506 return emptyWebResourceResponse;
1508 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1509 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1510 // Increment the blocked requests counters.
1512 fanboysSocialBlockingListBlockedRequests++;
1514 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1515 activity.runOnUiThread(() -> {
1516 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1517 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1518 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1521 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1522 whiteListResultStringArray = null;
1524 // The resource request was blocked. Return an empty web resource response.
1525 return emptyWebResourceResponse;
1529 // Add the request to the log because it hasn't been processed by any of the previous checks.
1530 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1531 resourceRequests.add(whiteListResultStringArray);
1532 } else { // The request didn't match any blocklist entry. Log it as a default request.
1533 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1536 // The resource request has not been blocked. `return null` loads the requested resource.
1540 // Handle HTTP authentication requests.
1542 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1543 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1544 httpAuthHandler = handler;
1546 // Display the HTTP authentication dialog.
1547 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1548 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1551 // Update the URL in urlTextBox when the page starts to load.
1553 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1554 // Reset the list of resource requests.
1555 resourceRequests.clear();
1557 // Initialize the counters for requests blocked by each blocklist.
1558 blockedRequests = 0;
1559 easyListBlockedRequests = 0;
1560 easyPrivacyBlockedRequests = 0;
1561 fanboysAnnoyanceListBlockedRequests = 0;
1562 fanboysSocialBlockingListBlockedRequests = 0;
1563 ultraPrivacyBlockedRequests = 0;
1564 thirdPartyBlockedRequests = 0;
1566 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1568 mainWebView.setVisibility(View.INVISIBLE);
1571 // Hide the keyboard. `0` indicates no additional flags.
1572 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1574 // Check to see if Privacy Browser is waiting on Orbot.
1575 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1576 // 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.
1577 formattedUrlString = url;
1579 // Display the formatted URL text.
1580 urlTextBox.setText(formattedUrlString);
1582 // Apply text highlighting to `urlTextBox`.
1585 // Apply any custom domain settings if the URL was loaded by navigating history.
1586 if (navigatingHistory) {
1587 // Reset `navigatingHistory`.
1588 navigatingHistory = false;
1590 // Apply the domain settings.
1591 applyDomainSettings(url, true, false);
1594 // 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.
1595 urlIsLoading = true;
1597 // Replace Refresh with Stop if the menu item has been created. (The WebView typically begins loading before the menu items are instantiated.)
1598 if (refreshMenuItem != null) {
1600 refreshMenuItem.setTitle(R.string.stop);
1602 // If the icon is displayed in the AppBar, set it according to the theme.
1603 if (displayAdditionalAppBarIcons) {
1605 refreshMenuItem.setIcon(R.drawable.close_dark);
1607 refreshMenuItem.setIcon(R.drawable.close_light);
1614 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1616 public void onPageFinished(WebView view, String url) {
1617 // Reset the wide view port if it has been turned off by the waiting for Orbot message.
1618 if (!waitingForOrbot) {
1619 mainWebView.getSettings().setUseWideViewPort(true);
1622 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1623 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1624 cookieManager.flush();
1627 // Update the Refresh menu item if it has been created.
1628 if (refreshMenuItem != null) {
1629 // Reset the Refresh title.
1630 refreshMenuItem.setTitle(R.string.refresh);
1632 // If the icon is displayed in the AppBar, reset it according to the theme.
1633 if (displayAdditionalAppBarIcons) {
1635 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1637 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1642 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1643 urlIsLoading = false;
1645 // Clear the cache and history if Incognito Mode is enabled.
1646 if (incognitoModeEnabled) {
1647 // Clear the cache. `true` includes disk files.
1648 mainWebView.clearCache(true);
1650 // Clear the back/forward history.
1651 mainWebView.clearHistory();
1653 // Manually delete cache folders.
1655 // Delete the main cache directory.
1656 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1658 // Delete the secondary `Service Worker` cache directory.
1659 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1660 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1661 } catch (IOException e) {
1662 // Do nothing if an error is thrown.
1666 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1667 if (!waitingForOrbot) {
1668 // Check to see if `WebView` has set `url` to be `about:blank`.
1669 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1670 // Set `formattedUrlString` to `""`.
1671 formattedUrlString = "";
1673 urlTextBox.setText(formattedUrlString);
1675 // Request focus for `urlTextBox`.
1676 urlTextBox.requestFocus();
1678 // Display the keyboard.
1679 inputMethodManager.showSoftInput(urlTextBox, 0);
1681 // Apply the domain settings. This clears any settings from the previous domain.
1682 applyDomainSettings(formattedUrlString, true, false);
1683 } else { // `WebView` has loaded a webpage.
1684 // Set `formattedUrlString`.
1685 formattedUrlString = url;
1687 // Only update `urlTextBox` if the user is not typing in it.
1688 if (!urlTextBox.hasFocus()) {
1689 // Display the formatted URL text.
1690 urlTextBox.setText(formattedUrlString);
1692 // Apply text highlighting to `urlTextBox`.
1697 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1698 sslCertificate = mainWebView.getCertificate();
1700 // 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.
1701 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1702 // Initialize the current SSL certificate variables.
1703 String currentWebsiteIssuedToCName = "";
1704 String currentWebsiteIssuedToOName = "";
1705 String currentWebsiteIssuedToUName = "";
1706 String currentWebsiteIssuedByCName = "";
1707 String currentWebsiteIssuedByOName = "";
1708 String currentWebsiteIssuedByUName = "";
1709 Date currentWebsiteSslStartDate = null;
1710 Date currentWebsiteSslEndDate = null;
1713 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1714 if (sslCertificate != null) {
1715 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1716 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1717 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1718 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1719 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1720 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1721 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1722 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1725 // 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`.
1726 String currentWebsiteSslStartDateString = "";
1727 String currentWebsiteSslEndDateString = "";
1728 String pinnedDomainSslStartDateString = "";
1729 String pinnedDomainSslEndDateString = "";
1731 // Convert the `Dates` to `Strings` if they are not `null`.
1732 if (currentWebsiteSslStartDate != null) {
1733 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1736 if (currentWebsiteSslEndDate != null) {
1737 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1740 if (pinnedDomainSslStartDate != null) {
1741 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1744 if (pinnedDomainSslEndDate != null) {
1745 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1748 // Check to see if the pinned SSL certificate matches the current website certificate.
1749 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1750 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1751 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1752 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1753 // The pinned SSL certificate doesn't match the current domain certificate.
1754 //Display the pinned SSL certificate mismatch `AlertDialog`.
1755 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1756 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1762 // Handle SSL Certificate errors.
1764 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1765 // Get the current website SSL certificate.
1766 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1768 // Extract the individual pieces of information from the current website SSL certificate.
1769 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1770 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1771 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1772 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1773 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1774 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1775 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1776 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1778 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1779 if (pinnedDomainSslCertificate &&
1780 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1781 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1782 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1783 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1784 // An SSL certificate is pinned and matches the current domain certificate.
1785 // Proceed to the website without displaying an error.
1787 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1788 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1789 sslErrorHandler = handler;
1791 // Display the SSL error `AlertDialog`.
1792 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1793 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1798 // Load the website if not waiting for Orbot to connect.
1799 if (!waitingForOrbot) {
1800 loadUrl(formattedUrlString);
1805 protected void onNewIntent(Intent intent) {
1806 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1809 // Check to see if the intent contains a new URL.
1810 if (intent.getData() != null) {
1811 // Get the intent data.
1812 final Uri intentUriData = intent.getData();
1814 // Load the website.
1815 loadUrl(intentUriData.toString());
1817 // Close the navigation drawer if it is open.
1818 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1819 drawerLayout.closeDrawer(GravityCompat.START);
1822 // Close the bookmarks drawer if it is open.
1823 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1824 drawerLayout.closeDrawer(GravityCompat.END);
1827 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1828 mainWebView.requestFocus();
1833 public void onRestart() {
1834 // Run the default commands.
1837 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1838 if (proxyThroughOrbot) {
1839 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1840 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1842 // Send the intent to the Orbot package.
1843 orbotIntent.setPackage("org.torproject.android");
1846 sendBroadcast(orbotIntent);
1849 // Apply the app settings if returning from the Settings activity..
1850 if (reapplyAppSettingsOnRestart) {
1851 // Apply the app settings.
1854 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1855 if (reloadOnRestart) {
1856 // Reload `mainWebView`.
1857 mainWebView.reload();
1859 // Reset `reloadOnRestartBoolean`.
1860 reloadOnRestart = false;
1863 // Reset the return from settings flag.
1864 reapplyAppSettingsOnRestart = false;
1867 // Apply the domain settings if returning from the Domains activity.
1868 if (reapplyDomainSettingsOnRestart) {
1869 // Reapply the domain settings.
1870 applyDomainSettings(formattedUrlString, false, true);
1872 // Reset `reapplyDomainSettingsOnRestart`.
1873 reapplyDomainSettingsOnRestart = false;
1876 // Load the URL on restart to apply changes to night mode.
1877 if (loadUrlOnRestart) {
1878 // Load the current `formattedUrlString`.
1879 loadUrl(formattedUrlString);
1881 // Reset `loadUrlOnRestart.
1882 loadUrlOnRestart = false;
1885 // Update the bookmarks drawer if returning from the Bookmarks activity.
1886 if (restartFromBookmarksActivity) {
1887 // Close the bookmarks drawer.
1888 drawerLayout.closeDrawer(GravityCompat.END);
1890 // Reload the bookmarks drawer.
1891 loadBookmarksFolder();
1893 // Reset `restartFromBookmarksActivity`.
1894 restartFromBookmarksActivity = false;
1897 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1898 updatePrivacyIcons(true);
1901 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1903 public void onResume() {
1904 // Run the default commands.
1907 // Resume JavaScript (if enabled).
1908 mainWebView.resumeTimers();
1910 // Resume `mainWebView`.
1911 mainWebView.onResume();
1913 // Resume the adView for the free flavor.
1914 if (BuildConfig.FLAVOR.contentEquals("free")) {
1916 AdHelper.resumeAd(findViewById(R.id.adview));
1919 // Display a message to the user if waiting for Orbot.
1920 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1921 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
1922 mainWebView.getSettings().setUseWideViewPort(false);
1924 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1925 mainWebView.loadData(waitingForOrbotHtmlString, "text/html", null);
1928 if (displayingFullScreenVideo) {
1929 // Remove the translucent overlays.
1930 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1932 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1933 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1935 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1936 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1937 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1939 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1944 public void onPause() {
1945 // Run the default commands.
1948 // Pause `mainWebView`.
1949 mainWebView.onPause();
1951 // Stop all JavaScript.
1952 mainWebView.pauseTimers();
1954 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1955 if (BuildConfig.FLAVOR.contentEquals("free")) {
1957 AdHelper.pauseAd(findViewById(R.id.adview));
1962 public void onDestroy() {
1963 // Unregister the Orbot status broadcast receiver.
1964 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1966 // Close the bookmarks cursor and database.
1967 bookmarksCursor.close();
1968 bookmarksDatabaseHelper.close();
1970 // Run the default commands.
1975 public boolean onCreateOptionsMenu(Menu menu) {
1976 // Inflate the menu; this adds items to the action bar if it is present.
1977 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1979 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1982 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1983 updatePrivacyIcons(false);
1985 // Get handles for the menu items.
1986 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1987 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1988 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1989 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1990 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1991 refreshMenuItem = menu.findItem(R.id.refresh);
1992 blocklistsMenuItem = menu.findItem(R.id.blocklists);
1993 easyListMenuItem = menu.findItem(R.id.easylist);
1994 easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1995 fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1996 fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1997 ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1998 blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1999 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
2001 // Only display third-party cookies if API >= 21
2002 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
2004 // Only display the form data menu items if the API < 26.
2005 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
2006 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
2008 // Only show Ad Consent if this is the free flavor.
2009 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
2011 // Get the shared preference values.
2012 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2014 // Get the status of the additional AppBar icons.
2015 displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
2017 // Set the status of the additional app bar icons. Setting the refresh menu item to `SHOW_AS_ACTION_ALWAYS` makes it appear even on small devices like phones.
2018 if (displayAdditionalAppBarIcons) {
2019 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2020 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2021 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
2022 } else { //Do not display the additional icons.
2023 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2024 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2025 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2028 // Replace Refresh with Stop if a URL is already loading.
2031 refreshMenuItem.setTitle(R.string.stop);
2033 // If the icon is displayed in the AppBar, set it according to the theme.
2034 if (displayAdditionalAppBarIcons) {
2036 refreshMenuItem.setIcon(R.drawable.close_dark);
2038 refreshMenuItem.setIcon(R.drawable.close_light);
2047 public boolean onPrepareOptionsMenu(Menu menu) {
2048 // Get handles for the menu items.
2049 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2050 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2051 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2052 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2053 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
2054 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2055 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2056 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2057 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
2058 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2059 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
2060 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2061 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
2062 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
2064 // Set the text for the domain menu item.
2065 if (domainSettingsApplied) {
2066 addOrEditDomain.setTitle(R.string.edit_domain_settings);
2068 addOrEditDomain.setTitle(R.string.add_domain_settings);
2071 // Set the status of the menu item checkboxes.
2072 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2073 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2074 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2075 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
2076 easyListMenuItem.setChecked(easyListEnabled);
2077 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
2078 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
2079 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
2080 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
2081 blockAllThirdPartyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
2082 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
2083 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2084 nightModeMenuItem.setChecked(nightMode);
2085 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
2087 // Enable third-party cookies if first-party cookies are enabled.
2088 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2090 // Enable DOM Storage if JavaScript is enabled.
2091 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2093 // Enable Clear Cookies if there are any.
2094 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2096 // Get a count of the number of files in the Local Storage directory.
2097 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2098 int localStorageDirectoryNumberOfFiles = 0;
2099 if (localStorageDirectory.exists()) {
2100 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2103 // Get a count of the number of files in the IndexedDB directory.
2104 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2105 int indexedDBDirectoryNumberOfFiles = 0;
2106 if (indexedDBDirectory.exists()) {
2107 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2110 // Enable Clear DOM Storage if there is any.
2111 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2113 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
2114 if (Build.VERSION.SDK_INT < 26) {
2115 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2116 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2118 // Disable clear form data because it is not supported on current version of Android.
2119 clearFormDataMenuItem.setEnabled(false);
2122 // Enable Clear Data if any of the submenu items are enabled.
2123 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2125 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2126 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2128 // Initialize the display names for the blocklists with the number of blocked requests.
2129 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
2130 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2131 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2132 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2133 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2134 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2135 blockAllThirdPartyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2137 // Get the current user agent.
2138 String currentUserAgent = mainWebView.getSettings().getUserAgentString();
2140 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
2141 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
2142 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
2143 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
2144 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
2145 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
2146 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
2147 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
2148 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
2149 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
2150 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
2151 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
2152 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
2153 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
2154 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
2155 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
2156 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
2157 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
2158 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
2159 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
2160 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
2161 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
2162 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
2163 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
2164 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
2165 } else { // Custom user agent.
2166 menu.findItem(R.id.user_agent_custom).setChecked(true);
2169 // Initialize font size variables.
2170 int fontSize = mainWebView.getSettings().getTextZoom();
2171 String fontSizeTitle;
2172 MenuItem selectedFontSizeMenuItem;
2174 // Prepare the font size title and current size menu item.
2177 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2178 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2182 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2183 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2187 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2188 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2192 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2193 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2197 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2198 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2202 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2203 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2207 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2208 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2212 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2213 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2217 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2218 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2222 // Set the font size title and select the current size menu item.
2223 fontSizeMenuItem.setTitle(fontSizeTitle);
2224 selectedFontSizeMenuItem.setChecked(true);
2226 // Run all the other default commands.
2227 super.onPrepareOptionsMenu(menu);
2229 // Display the menu.
2234 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2235 @SuppressLint("SetJavaScriptEnabled")
2236 // removeAllCookies is deprecated, but it is required for API < 21.
2237 @SuppressWarnings("deprecation")
2238 public boolean onOptionsItemSelected(MenuItem menuItem) {
2239 // Get the selected menu item ID.
2240 int menuItemId = menuItem.getItemId();
2242 // Set the commands that relate to the menu entries.
2243 switch (menuItemId) {
2244 case R.id.toggle_javascript:
2245 // Switch the status of javaScriptEnabled.
2246 javaScriptEnabled = !javaScriptEnabled;
2248 // Apply the new JavaScript status.
2249 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2251 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2252 updatePrivacyIcons(true);
2254 // Display a `Snackbar`.
2255 if (javaScriptEnabled) { // JavaScrip is enabled.
2256 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2257 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2258 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2259 } else { // Privacy mode.
2260 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2263 // Reload the WebView.
2264 mainWebView.reload();
2267 case R.id.add_or_edit_domain:
2268 if (domainSettingsApplied) { // Edit the current domain settings.
2269 // Reapply the domain settings on returning to `MainWebViewActivity`.
2270 reapplyDomainSettingsOnRestart = true;
2271 currentDomainName = "";
2273 // Create an intent to launch the domains activity.
2274 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2276 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2277 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2278 domainsIntent.putExtra("closeOnBack", true);
2281 startActivity(domainsIntent);
2282 } else { // Add a new domain.
2283 // Apply the new domain settings on returning to `MainWebViewActivity`.
2284 reapplyDomainSettingsOnRestart = true;
2285 currentDomainName = "";
2287 // Get the current domain
2288 Uri currentUri = Uri.parse(formattedUrlString);
2289 String currentDomain = currentUri.getHost();
2291 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2292 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2294 // Create the domain and store the database ID.
2295 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2297 // Create an intent to launch the domains activity.
2298 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2300 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2301 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2302 domainsIntent.putExtra("closeOnBack", true);
2305 startActivity(domainsIntent);
2309 case R.id.toggle_first_party_cookies:
2310 // Switch the status of firstPartyCookiesEnabled.
2311 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2313 // Update the menu checkbox.
2314 menuItem.setChecked(firstPartyCookiesEnabled);
2316 // Apply the new cookie status.
2317 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2319 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2320 updatePrivacyIcons(true);
2322 // Display a `Snackbar`.
2323 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2324 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2325 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2326 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2327 } else { // Privacy mode.
2328 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2331 // Reload the WebView.
2332 mainWebView.reload();
2335 case R.id.toggle_third_party_cookies:
2336 if (Build.VERSION.SDK_INT >= 21) {
2337 // Switch the status of thirdPartyCookiesEnabled.
2338 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2340 // Update the menu checkbox.
2341 menuItem.setChecked(thirdPartyCookiesEnabled);
2343 // Apply the new cookie status.
2344 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2346 // Display a `Snackbar`.
2347 if (thirdPartyCookiesEnabled) {
2348 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2350 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2353 // Reload the WebView.
2354 mainWebView.reload();
2355 } // Else do nothing because SDK < 21.
2358 case R.id.toggle_dom_storage:
2359 // Switch the status of domStorageEnabled.
2360 domStorageEnabled = !domStorageEnabled;
2362 // Update the menu checkbox.
2363 menuItem.setChecked(domStorageEnabled);
2365 // Apply the new DOM Storage status.
2366 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2368 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2369 updatePrivacyIcons(true);
2371 // Display a `Snackbar`.
2372 if (domStorageEnabled) {
2373 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2375 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2378 // Reload the WebView.
2379 mainWebView.reload();
2382 // Form data can be removed once the minimum API >= 26.
2383 case R.id.toggle_save_form_data:
2384 // Switch the status of saveFormDataEnabled.
2385 saveFormDataEnabled = !saveFormDataEnabled;
2387 // Update the menu checkbox.
2388 menuItem.setChecked(saveFormDataEnabled);
2390 // Apply the new form data status.
2391 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2393 // Display a `Snackbar`.
2394 if (saveFormDataEnabled) {
2395 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2397 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2400 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2401 updatePrivacyIcons(true);
2403 // Reload the WebView.
2404 mainWebView.reload();
2407 case R.id.clear_cookies:
2408 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2409 .setAction(R.string.undo, v -> {
2410 // Do nothing because everything will be handled by `onDismissed()` below.
2412 .addCallback(new Snackbar.Callback() {
2414 public void onDismissed(Snackbar snackbar, int event) {
2416 // The user pushed the `Undo` button.
2417 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2421 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2423 // `cookieManager.removeAllCookie()` varies by SDK.
2424 if (Build.VERSION.SDK_INT < 21) {
2425 cookieManager.removeAllCookie();
2427 // `null` indicates no callback.
2428 cookieManager.removeAllCookies(null);
2436 case R.id.clear_dom_storage:
2437 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2438 .setAction(R.string.undo, v -> {
2439 // Do nothing because everything will be handled by `onDismissed()` below.
2441 .addCallback(new Snackbar.Callback() {
2443 public void onDismissed(Snackbar snackbar, int event) {
2445 // The user pushed the `Undo` button.
2446 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2450 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2452 // Delete the DOM Storage.
2453 WebStorage webStorage = WebStorage.getInstance();
2454 webStorage.deleteAllData();
2456 // Initialize a handler to manually delete the DOM storage files and directories.
2457 Handler deleteDomStorageHandler = new Handler();
2459 // Setup a runnable to manually delete the DOM storage files and directories.
2460 Runnable deleteDomStorageRunnable = () -> {
2462 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2463 privacyBrowserRuntime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2465 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2466 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2467 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2468 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2469 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2470 } catch (IOException e) {
2471 // Do nothing if an error is thrown.
2475 // Manually delete the DOM storage files after 200 milliseconds.
2476 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
2483 // Form data can be remove once the minimum API >= 26.
2484 case R.id.clear_form_data:
2485 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2486 .setAction(R.string.undo, v -> {
2487 // Do nothing because everything will be handled by `onDismissed()` below.
2489 .addCallback(new Snackbar.Callback() {
2491 public void onDismissed(Snackbar snackbar, int event) {
2493 // The user pushed the `Undo` button.
2494 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2498 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2500 // Delete the form data.
2501 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2502 mainWebViewDatabase.clearFormData();
2510 // Toggle the EasyList status.
2511 easyListEnabled = !easyListEnabled;
2513 // Update the menu checkbox.
2514 menuItem.setChecked(easyListEnabled);
2516 // Reload the main WebView.
2517 mainWebView.reload();
2520 case R.id.easyprivacy:
2521 // Toggle the EasyPrivacy status.
2522 easyPrivacyEnabled = !easyPrivacyEnabled;
2524 // Update the menu checkbox.
2525 menuItem.setChecked(easyPrivacyEnabled);
2527 // Reload the main WebView.
2528 mainWebView.reload();
2531 case R.id.fanboys_annoyance_list:
2532 // Toggle Fanboy's Annoyance List status.
2533 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2535 // Update the menu checkbox.
2536 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2538 // Update the staus of Fanboy's Social Blocking List.
2539 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2540 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2542 // Reload the main WebView.
2543 mainWebView.reload();
2546 case R.id.fanboys_social_blocking_list:
2547 // Toggle Fanboy's Social Blocking List status.
2548 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2550 // Update the menu checkbox.
2551 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2553 // Reload the main WebView.
2554 mainWebView.reload();
2557 case R.id.ultraprivacy:
2558 // Toggle the UltraPrivacy status.
2559 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2561 // Update the menu checkbox.
2562 menuItem.setChecked(ultraPrivacyEnabled);
2564 // Reload the main WebView.
2565 mainWebView.reload();
2568 case R.id.block_all_third_party_requests:
2569 //Toggle the third-party requests blocker status.
2570 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2572 // Update the menu checkbox.
2573 menuItem.setChecked(blockAllThirdPartyRequests);
2575 // Reload the main WebView.
2576 mainWebView.reload();
2579 case R.id.user_agent_privacy_browser:
2580 // Update the user agent.
2581 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
2583 // Reload the WebView.
2584 mainWebView.reload();
2587 case R.id.user_agent_webview_default:
2588 // Update the user agent.
2589 mainWebView.getSettings().setUserAgentString("");
2591 // Reload the WebView.
2592 mainWebView.reload();
2595 case R.id.user_agent_firefox_on_android:
2596 // Update the user agent.
2597 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
2599 // Reload the WebView.
2600 mainWebView.reload();
2603 case R.id.user_agent_chrome_on_android:
2604 // Update the user agent.
2605 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
2607 // Reload the WebView.
2608 mainWebView.reload();
2611 case R.id.user_agent_safari_on_ios:
2612 // Update the user agent.
2613 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
2615 // Reload the WebView.
2616 mainWebView.reload();
2619 case R.id.user_agent_firefox_on_linux:
2620 // Update the user agent.
2621 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
2623 // Reload the WebView.
2624 mainWebView.reload();
2627 case R.id.user_agent_chromium_on_linux:
2628 // Update the user agent.
2629 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
2631 // Reload the WebView.
2632 mainWebView.reload();
2635 case R.id.user_agent_firefox_on_windows:
2636 // Update the user agent.
2637 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
2639 // Reload the WebView.
2640 mainWebView.reload();
2643 case R.id.user_agent_chrome_on_windows:
2644 // Update the user agent.
2645 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
2647 // Reload the WebView.
2648 mainWebView.reload();
2651 case R.id.user_agent_edge_on_windows:
2652 // Update the user agent.
2653 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
2655 // Reload the WebView.
2656 mainWebView.reload();
2659 case R.id.user_agent_internet_explorer_on_windows:
2660 // Update the user agent.
2661 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
2663 // Reload the WebView.
2664 mainWebView.reload();
2667 case R.id.user_agent_safari_on_macos:
2668 // Update the user agent.
2669 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
2671 // Reload the WebView.
2672 mainWebView.reload();
2675 case R.id.user_agent_custom:
2676 // Update the user agent.
2677 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2679 // Reload the WebView.
2680 mainWebView.reload();
2683 case R.id.font_size_twenty_five_percent:
2684 mainWebView.getSettings().setTextZoom(25);
2687 case R.id.font_size_fifty_percent:
2688 mainWebView.getSettings().setTextZoom(50);
2691 case R.id.font_size_seventy_five_percent:
2692 mainWebView.getSettings().setTextZoom(75);
2695 case R.id.font_size_one_hundred_percent:
2696 mainWebView.getSettings().setTextZoom(100);
2699 case R.id.font_size_one_hundred_twenty_five_percent:
2700 mainWebView.getSettings().setTextZoom(125);
2703 case R.id.font_size_one_hundred_fifty_percent:
2704 mainWebView.getSettings().setTextZoom(150);
2707 case R.id.font_size_one_hundred_seventy_five_percent:
2708 mainWebView.getSettings().setTextZoom(175);
2711 case R.id.font_size_two_hundred_percent:
2712 mainWebView.getSettings().setTextZoom(200);
2715 case R.id.swipe_to_refresh:
2716 // Toggle swipe to refresh.
2717 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2720 case R.id.display_images:
2721 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2722 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2723 mainWebView.reload();
2724 } else { // Images are not currently loaded automatically.
2725 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2729 case R.id.night_mode:
2730 // Toggle night mode.
2731 nightMode = !nightMode;
2733 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
2734 if (nightMode) { // Night mode is enabled. Enable JavaScript.
2735 // Update the global variable.
2736 javaScriptEnabled = true;
2737 } else if (domainSettingsApplied) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
2738 // Get the JavaScript preference that was stored the last time domain settings were loaded.
2739 javaScriptEnabled = domainSettingsJavaScriptEnabled;
2740 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
2741 // Get a handle for the shared preference.
2742 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2744 // Get the JavaScript preference.
2745 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2748 // Apply the JavaScript setting to the WebView.
2749 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2751 // Update the privacy icons.
2752 updatePrivacyIcons(false);
2754 // Reload the website.
2755 mainWebView.reload();
2759 // Get a `PrintManager` instance.
2760 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2762 // Convert `mainWebView` to `printDocumentAdapter`.
2763 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2765 // Remove the lint error below that `printManager` might be `null`.
2766 assert printManager != null;
2768 // Print the document. The print attributes are `null`.
2769 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2772 case R.id.view_source:
2773 // Launch the View Source activity.
2774 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2775 startActivity(viewSourceIntent);
2778 case R.id.proxy_through_orbot:
2779 // Toggle the proxy through Orbot variable.
2780 proxyThroughOrbot = !proxyThroughOrbot;
2782 // Apply the proxy through Orbot settings.
2783 applyProxyThroughOrbot(true);
2787 // Setup the share string.
2788 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2790 // Create the share intent.
2791 Intent shareIntent = new Intent(Intent.ACTION_SEND);
2792 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2793 shareIntent.setType("text/plain");
2796 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2799 case R.id.find_on_page:
2800 // Hide the URL app bar.
2801 supportAppBar.setVisibility(View.GONE);
2803 // Show the Find on Page `RelativeLayout`.
2804 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2806 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2807 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2808 findOnPageEditText.postDelayed(() -> {
2809 // Set the focus on `findOnPageEditText`.
2810 findOnPageEditText.requestFocus();
2812 // Display the keyboard. `0` sets no input flags.
2813 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2817 case R.id.add_to_homescreen:
2818 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2819 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2820 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2822 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2826 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2827 // Reload the WebView.
2828 mainWebView.reload();
2829 } else { // The stop button was pushed.
2830 // Stop the loading of the WebView.
2831 mainWebView.stopLoading();
2835 case R.id.ad_consent:
2836 // Display the ad consent dialog.
2837 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2838 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2842 // Don't consume the event.
2843 return super.onOptionsItemSelected(menuItem);
2847 // removeAllCookies is deprecated, but it is required for API < 21.
2848 @SuppressWarnings("deprecation")
2850 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2851 int menuItemId = menuItem.getItemId();
2853 switch (menuItemId) {
2859 if (mainWebView.canGoBack()) {
2860 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2861 formattedUrlString = "";
2863 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2864 navigatingHistory = true;
2866 // Load the previous website in the history.
2867 mainWebView.goBack();
2872 if (mainWebView.canGoForward()) {
2873 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2874 formattedUrlString = "";
2876 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2877 navigatingHistory = true;
2879 // Load the next website in the history.
2880 mainWebView.goForward();
2885 // Get the `WebBackForwardList`.
2886 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2888 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2889 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2890 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2894 // Launch the requests activity.
2895 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2896 startActivity(requestsIntent);
2899 case R.id.downloads:
2900 // Launch the system Download Manager.
2901 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2903 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2904 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2906 startActivity(downloadManagerIntent);
2910 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2911 reapplyDomainSettingsOnRestart = true;
2912 currentDomainName = "";
2914 // Launch the domains activity.
2915 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2916 startActivity(domainsIntent);
2920 // Set the flag to reapply app settings on restart when returning from Settings.
2921 reapplyAppSettingsOnRestart = true;
2923 // Set the flag to reapply the domain settings on restart when returning from Settings.
2924 reapplyDomainSettingsOnRestart = true;
2925 currentDomainName = "";
2927 // Launch the settings activity.
2928 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2929 startActivity(settingsIntent);
2932 case R.id.import_export:
2933 // Launch the import/export activity.
2934 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2935 startActivity(importExportIntent);
2939 // Launch `GuideActivity`.
2940 Intent guideIntent = new Intent(this, GuideActivity.class);
2941 startActivity(guideIntent);
2945 // Launch `AboutActivity`.
2946 Intent aboutIntent = new Intent(this, AboutActivity.class);
2947 startActivity(aboutIntent);
2950 case R.id.clearAndExit:
2951 // Close the bookmarks cursor and database.
2952 bookmarksCursor.close();
2953 bookmarksDatabaseHelper.close();
2955 // Get a handle for `sharedPreferences`. `this` references the current context.
2956 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2958 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2961 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2962 // The command to remove cookies changed slightly in API 21.
2963 if (Build.VERSION.SDK_INT >= 21) {
2964 cookieManager.removeAllCookies(null);
2966 cookieManager.removeAllCookie();
2969 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2971 // We have to use two commands because `Runtime.exec()` does not like `*`.
2972 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2973 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2974 } catch (IOException e) {
2975 // Do nothing if an error is thrown.
2979 // Clear DOM storage.
2980 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2981 // Ask `WebStorage` to clear the DOM storage.
2982 WebStorage webStorage = WebStorage.getInstance();
2983 webStorage.deleteAllData();
2985 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2987 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2988 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2990 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2991 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2992 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2993 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2994 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2995 } catch (IOException e) {
2996 // Do nothing if an error is thrown.
3000 // Clear form data if the API < 26.
3001 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
3002 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
3003 webViewDatabase.clearFormData();
3005 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
3007 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
3008 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
3009 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
3010 } catch (IOException e) {
3011 // Do nothing if an error is thrown.
3016 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
3017 // `true` includes disk files.
3018 mainWebView.clearCache(true);
3020 // Manually delete the cache directories.
3022 // Delete the main cache directory.
3023 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
3025 // Delete the secondary `Service Worker` cache directory.
3026 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
3027 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
3028 } catch (IOException e) {
3029 // Do nothing if an error is thrown.
3033 // Clear SSL certificate preferences.
3034 mainWebView.clearSslPreferences();
3036 // Clear the back/forward history.
3037 mainWebView.clearHistory();
3039 // Clear `formattedUrlString`.
3040 formattedUrlString = null;
3042 // Clear `customHeaders`.
3043 customHeaders.clear();
3045 // Detach all views from `mainWebViewRelativeLayout`.
3046 mainWebViewRelativeLayout.removeAllViews();
3048 // Destroy the internal state of `mainWebView`.
3049 mainWebView.destroy();
3051 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
3052 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
3053 if (clearEverything) {
3055 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
3056 } catch (IOException e) {
3057 // Do nothing if an error is thrown.
3061 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
3062 if (Build.VERSION.SDK_INT >= 21) {
3063 finishAndRemoveTask();
3068 // Remove the terminated program from RAM. The status code is `0`.
3073 // Close the navigation drawer.
3074 drawerLayout.closeDrawer(GravityCompat.START);
3079 public void onPostCreate(Bundle savedInstanceState) {
3080 super.onPostCreate(savedInstanceState);
3082 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
3083 drawerToggle.syncState();
3087 public void onConfigurationChanged(Configuration newConfig) {
3088 super.onConfigurationChanged(newConfig);
3090 // Reload the ad for the free flavor if we not in full screen mode.
3091 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
3092 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3093 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
3096 // `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:
3097 // https://code.google.com/p/android/issues/detail?id=20493#c8
3098 // ActivityCompat.invalidateOptionsMenu(this);
3102 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
3103 // Store the `HitTestResult`.
3104 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
3107 final String imageUrl;
3108 final String linkUrl;
3110 // Get a handle for the `ClipboardManager`.
3111 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
3113 // Remove the lint errors below that `clipboardManager` might be `null`.
3114 assert clipboardManager != null;
3116 switch (hitTestResult.getType()) {
3117 // `SRC_ANCHOR_TYPE` is a link.
3118 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
3119 // Get the target URL.
3120 linkUrl = hitTestResult.getExtra();
3122 // Set the target URL as the title of the `ContextMenu`.
3123 menu.setHeaderTitle(linkUrl);
3125 // Add a Load URL entry.
3126 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
3131 // Add a Copy URL entry.
3132 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
3133 // Save the link URL in a `ClipData`.
3134 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
3136 // Set the `ClipData` as the clipboard's primary clip.
3137 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
3141 // Add a Download URL entry.
3142 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
3143 // Check if the download should be processed by an external app.
3144 if (downloadWithExternalApp) { // Download with an external app.
3145 openUrlWithExternalApp(linkUrl);
3146 } else { // Download with Android's download manager.
3147 // Check to see if the storage permission has already been granted.
3148 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
3149 // Store the variables for future use by `onRequestPermissionsResult()`.
3150 downloadUrl = linkUrl;
3151 downloadContentDisposition = "none";
3152 downloadContentLength = -1;
3154 // Show a dialog if the user has previously denied the permission.
3155 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3156 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
3157 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
3159 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
3160 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3161 } else { // Show the permission request directly.
3162 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
3163 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3165 } else { // The storage permission has already been granted.
3166 // Get a handle for the download file alert dialog.
3167 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
3169 // Show the download file alert dialog.
3170 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3176 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3177 menu.add(R.string.cancel);
3180 case WebView.HitTestResult.EMAIL_TYPE:
3181 // Get the target URL.
3182 linkUrl = hitTestResult.getExtra();
3184 // Set the target URL as the title of the `ContextMenu`.
3185 menu.setHeaderTitle(linkUrl);
3187 // Add a `Write Email` entry.
3188 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
3189 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
3190 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
3192 // Parse the url and set it as the data for the `Intent`.
3193 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
3195 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
3196 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3199 startActivity(emailIntent);
3203 // Add a `Copy Email Address` entry.
3204 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
3205 // Save the email address in a `ClipData`.
3206 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
3208 // Set the `ClipData` as the clipboard's primary clip.
3209 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
3213 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3214 menu.add(R.string.cancel);
3217 // `IMAGE_TYPE` is an image.
3218 case WebView.HitTestResult.IMAGE_TYPE:
3219 // Get the image URL.
3220 imageUrl = hitTestResult.getExtra();
3222 // Set the image URL as the title of the `ContextMenu`.
3223 menu.setHeaderTitle(imageUrl);
3225 // Add a `View Image` entry.
3226 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3231 // Add a `Download Image` entry.
3232 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3233 // Check if the download should be processed by an external app.
3234 if (downloadWithExternalApp) { // Download with an external app.
3235 openUrlWithExternalApp(imageUrl);
3236 } else { // Download with Android's download manager.
3237 // Check to see if the storage permission has already been granted.
3238 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
3239 // Store the image URL for use by `onRequestPermissionResult()`.
3240 downloadImageUrl = imageUrl;
3242 // Show a dialog if the user has previously denied the permission.
3243 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3244 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3245 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3247 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3248 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3249 } else { // Show the permission request directly.
3250 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3251 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3253 } else { // The storage permission has already been granted.
3254 // Get a handle for the download image alert dialog.
3255 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3257 // Show the download image alert dialog.
3258 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3264 // Add a `Copy URL` entry.
3265 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3266 // Save the image URL in a `ClipData`.
3267 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3269 // Set the `ClipData` as the clipboard's primary clip.
3270 clipboardManager.setPrimaryClip(srcImageTypeClipData);
3274 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3275 menu.add(R.string.cancel);
3279 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
3280 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
3281 // Get the image URL.
3282 imageUrl = hitTestResult.getExtra();
3284 // Set the image URL as the title of the `ContextMenu`.
3285 menu.setHeaderTitle(imageUrl);
3287 // Add a `View Image` entry.
3288 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3293 // Add a `Download Image` entry.
3294 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3295 // Check if the download should be processed by an external app.
3296 if (downloadWithExternalApp) { // Download with an external app.
3297 openUrlWithExternalApp(imageUrl);
3298 } else { // Download with Android's download manager.
3299 // Check to see if the storage permission has already been granted.
3300 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
3301 // Store the image URL for use by `onRequestPermissionResult()`.
3302 downloadImageUrl = imageUrl;
3304 // Show a dialog if the user has previously denied the permission.
3305 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3306 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3307 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3309 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3310 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3311 } else { // Show the permission request directly.
3312 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3313 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3315 } else { // The storage permission has already been granted.
3316 // Get a handle for the download image alert dialog.
3317 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3319 // Show the download image alert dialog.
3320 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3326 // Add a `Copy URL` entry.
3327 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3328 // Save the image URL in a `ClipData`.
3329 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3331 // Set the `ClipData` as the clipboard's primary clip.
3332 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3336 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3337 menu.add(R.string.cancel);
3343 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3344 // Get the `EditTexts` from the `dialogFragment`.
3345 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3346 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3348 // Extract the strings from the `EditTexts`.
3349 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3350 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3352 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3353 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3354 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3355 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3357 // Display the new bookmark below the current items in the (0 indexed) list.
3358 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3360 // Create the bookmark.
3361 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3363 // Update `bookmarksCursor` with the current contents of this folder.
3364 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3366 // Update the `ListView`.
3367 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3369 // Scroll to the new bookmark.
3370 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3374 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3375 // Get handles for the views in `dialogFragment`.
3376 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3377 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3378 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3380 // Get new folder name string.
3381 String folderNameString = createFolderNameEditText.getText().toString();
3383 // Get the new folder icon `Bitmap`.
3384 Bitmap folderIconBitmap;
3385 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3386 // Get the default folder icon and convert it to a `Bitmap`.
3387 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3388 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3389 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3390 } else { // Use the `WebView` favorite icon.
3391 folderIconBitmap = favoriteIconBitmap;
3394 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3395 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3396 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3397 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3399 // Move all the bookmarks down one in the display order.
3400 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3401 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3402 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3405 // Create the folder, which will be placed at the top of the `ListView`.
3406 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3408 // Update `bookmarksCursor` with the current contents of this folder.
3409 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3411 // Update the `ListView`.
3412 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3414 // Scroll to the new folder.
3415 bookmarksListView.setSelection(0);
3419 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3420 // Get the shortcut name.
3421 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3422 String shortcutNameString = shortcutNameEditText.getText().toString();
3424 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3425 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3427 // Setup the shortcut intent.
3428 Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
3429 shortcutIntent.setData(Uri.parse(formattedUrlString));
3431 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3432 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3434 // Add the required fields to the shortcut info builder.
3435 shortcutInfoBuilder.setIcon(favoriteIcon);
3436 shortcutInfoBuilder.setIntent(shortcutIntent);
3437 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3439 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3440 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3444 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3445 switch (downloadType) {
3446 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3447 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3448 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3451 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3452 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3453 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3459 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
3460 switch (requestCode) {
3461 case DOWNLOAD_FILE_REQUEST_CODE:
3462 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3463 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3465 // On API 23, displaying the fragment must be delayed or the app will crash.
3466 if (Build.VERSION.SDK_INT == 23) {
3467 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3469 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3472 // Reset the download variables.
3474 downloadContentDisposition = "";
3475 downloadContentLength = 0;
3478 case DOWNLOAD_IMAGE_REQUEST_CODE:
3479 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3480 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3482 // On API 23, displaying the fragment must be delayed or the app will crash.
3483 if (Build.VERSION.SDK_INT == 23) {
3484 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3486 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3489 // Reset the image URL variable.
3490 downloadImageUrl = "";
3496 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3497 // Download the image if it has an HTTP or HTTPS URI.
3498 if (imageUrl.startsWith("http")) {
3499 // Get a handle for the system `DOWNLOAD_SERVICE`.
3500 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3502 // Parse `imageUrl`.
3503 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3505 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3506 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3507 if (firstPartyCookiesEnabled) {
3508 // Get the cookies for `imageUrl`.
3509 String cookies = cookieManager.getCookie(imageUrl);
3511 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3512 downloadRequest.addRequestHeader("Cookie", cookies);
3515 // Get the file name from the dialog fragment.
3516 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3517 String imageName = downloadImageNameEditText.getText().toString();
3519 // Specify the download location.
3520 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3521 // Download to the public download directory.
3522 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3523 } else { // External write permission denied.
3524 // Download to the app's external download directory.
3525 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3528 // Allow `MediaScanner` to index the download if it is a media file.
3529 downloadRequest.allowScanningByMediaScanner();
3531 // Add the URL as the description for the download.
3532 downloadRequest.setDescription(imageUrl);
3534 // Show the download notification after the download is completed.
3535 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3537 // Remove the lint warning below that `downloadManager` might be `null`.
3538 assert downloadManager != null;
3540 // Initiate the download.
3541 downloadManager.enqueue(downloadRequest);
3542 } else { // The image is not an HTTP or HTTPS URI.
3543 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3548 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3549 // Download the file if it has an HTTP or HTTPS URI.
3550 if (downloadUrl.startsWith("http")) {
3551 // Get a handle for the system `DOWNLOAD_SERVICE`.
3552 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3554 // Parse `downloadUrl`.
3555 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3557 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3558 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3559 if (firstPartyCookiesEnabled) {
3560 // Get the cookies for `downloadUrl`.
3561 String cookies = cookieManager.getCookie(downloadUrl);
3563 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3564 downloadRequest.addRequestHeader("Cookie", cookies);
3567 // Get the file name from the dialog fragment.
3568 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3569 String fileName = downloadFileNameEditText.getText().toString();
3571 // Specify the download location.
3572 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3573 // Download to the public download directory.
3574 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3575 } else { // External write permission denied.
3576 // Download to the app's external download directory.
3577 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3580 // Allow `MediaScanner` to index the download if it is a media file.
3581 downloadRequest.allowScanningByMediaScanner();
3583 // Add the URL as the description for the download.
3584 downloadRequest.setDescription(downloadUrl);
3586 // Show the download notification after the download is completed.
3587 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3589 // Remove the lint warning below that `downloadManager` might be `null`.
3590 assert downloadManager != null;
3592 // Initiate the download.
3593 downloadManager.enqueue(downloadRequest);
3594 } else { // The download is not an HTTP or HTTPS URI.
3595 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3600 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3601 // Get handles for the views from `dialogFragment`.
3602 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3603 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3604 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3606 // Store the bookmark strings.
3607 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3608 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3610 // Update the bookmark.
3611 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3612 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3613 } else { // Update the bookmark using the `WebView` favorite icon.
3614 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3615 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3616 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3617 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3619 // Update the bookmark and the favorite icon.
3620 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3623 // Update `bookmarksCursor` with the current contents of this folder.
3624 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3626 // Update the `ListView`.
3627 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3631 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3632 // Get handles for the views from `dialogFragment`.
3633 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3634 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3635 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3636 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3638 // Get the new folder name.
3639 String newFolderNameString = editFolderNameEditText.getText().toString();
3641 // Check if the favorite icon has changed.
3642 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3643 // Update the name in the database.
3644 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3645 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3646 // Get the new folder icon `Bitmap`.
3647 Bitmap folderIconBitmap;
3648 if (defaultFolderIconRadioButton.isChecked()) {
3649 // Get the default folder icon and convert it to a `Bitmap`.
3650 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3651 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3652 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3653 } else { // Use the `WebView` favorite icon.
3654 folderIconBitmap = favoriteIconBitmap;
3657 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3658 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3659 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3660 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3662 // Update the folder icon in the database.
3663 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3664 } else { // The folder icon and the name have changed.
3665 // Get the new folder icon `Bitmap`.
3666 Bitmap folderIconBitmap;
3667 if (defaultFolderIconRadioButton.isChecked()) {
3668 // Get the default folder icon and convert it to a `Bitmap`.
3669 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3670 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3671 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3672 } else { // Use the `WebView` favorite icon.
3673 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3676 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3677 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3678 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3679 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3681 // Update the folder name and icon in the database.
3682 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3685 // Update `bookmarksCursor` with the current contents of this folder.
3686 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3688 // Update the `ListView`.
3689 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3693 public void onHttpAuthenticationCancel() {
3694 // Cancel the `HttpAuthHandler`.
3695 httpAuthHandler.cancel();
3699 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3700 // Get handles for the `EditTexts`.
3701 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3702 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3704 // Proceed with the HTTP authentication.
3705 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3708 public void viewSslCertificate(View view) {
3709 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3710 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3711 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3715 public void onSslErrorCancel() {
3716 sslErrorHandler.cancel();
3720 public void onSslErrorProceed() {
3721 sslErrorHandler.proceed();
3725 public void onSslMismatchBack() {
3726 if (mainWebView.canGoBack()) { // There is a back page in the history.
3727 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3728 formattedUrlString = "";
3730 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3731 navigatingHistory = true;
3734 mainWebView.goBack();
3735 } else { // There are no pages to go back to.
3736 // Load a blank page
3742 public void onSslMismatchProceed() {
3743 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3744 ignorePinnedSslCertificate = true;
3748 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3749 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3750 formattedUrlString = "";
3752 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3753 navigatingHistory = true;
3755 // Load the history entry.
3756 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3760 public void onClearHistory() {
3761 // Clear the history.
3762 mainWebView.clearHistory();
3765 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3767 public void onBackPressed() {
3768 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3769 // Close the navigation drawer.
3770 drawerLayout.closeDrawer(GravityCompat.START);
3771 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3772 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3773 // close the bookmarks drawer.
3774 drawerLayout.closeDrawer(GravityCompat.END);
3775 } else { // A subfolder is displayed.
3776 // Place the former parent folder in `currentFolder`.
3777 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3779 // Load the new folder.
3780 loadBookmarksFolder();
3783 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3784 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3785 formattedUrlString = "";
3787 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3788 navigatingHistory = true;
3791 mainWebView.goBack();
3792 } else { // There isn't anything to do in Privacy Browser.
3793 // Pass `onBackPressed()` to the system.
3794 super.onBackPressed();
3798 // Process the results of an upload file chooser. Currently there is only one `startActivityForResult` in this activity, so the request code, used to differentiate them, is ignored.
3800 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3801 // File uploads only work on API >= 21.
3802 if (Build.VERSION.SDK_INT >= 21) {
3803 // Pass the file to the WebView.
3804 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3808 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3809 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3810 String unformattedUrlString = urlTextBox.getText().toString().trim();
3812 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3813 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3814 // Add `https://` at the beginning if it is missing. Otherwise the app will segfault.
3815 if (!unformattedUrlString.startsWith("http")) {
3816 unformattedUrlString = "https://" + unformattedUrlString;
3819 // Initialize `unformattedUrl`.
3820 URL unformattedUrl = null;
3822 // 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.
3824 unformattedUrl = new URL(unformattedUrlString);
3825 } catch (MalformedURLException e) {
3826 e.printStackTrace();
3829 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3830 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3831 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3832 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3833 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3834 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3837 Uri.Builder formattedUri = new Uri.Builder();
3838 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3840 // Decode `formattedUri` as a `String` in `UTF-8`.
3841 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3842 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3843 // Load a blank string.
3844 formattedUrlString = "";
3845 } else { // Search for the contents of the URL box.
3846 // Sanitize the search input and convert it to a search.
3847 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3849 // Add the base search URL.
3850 formattedUrlString = searchURL + encodedUrlString;
3853 // 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.
3854 urlTextBox.clearFocus();
3857 loadUrl(formattedUrlString);
3860 private void loadUrl(String url) {// Apply any custom domain settings.
3861 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3862 formattedUrlString = url;
3864 // Apply the domain settings.
3865 applyDomainSettings(url, true, false);
3867 // If loading a website, set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3868 urlIsLoading = !url.equals("");
3871 mainWebView.loadUrl(url, customHeaders);
3874 public void findPreviousOnPage(View view) {
3875 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3876 mainWebView.findNext(false);
3879 public void findNextOnPage(View view) {
3880 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3881 mainWebView.findNext(true);
3884 public void closeFindOnPage(View view) {
3885 // Delete the contents of `find_on_page_edittext`.
3886 findOnPageEditText.setText(null);
3888 // Clear the highlighted phrases.
3889 mainWebView.clearMatches();
3891 // Hide the Find on Page `RelativeLayout`.
3892 findOnPageLinearLayout.setVisibility(View.GONE);
3894 // Show the URL app bar.
3895 supportAppBar.setVisibility(View.VISIBLE);
3897 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3898 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3901 private void applyAppSettings() {
3902 // Get a handle for the shared preferences.
3903 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3905 // Store the values from the shared preferences in variables.
3906 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3907 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3908 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3909 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3910 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3911 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3912 downloadWithExternalApp = sharedPreferences.getBoolean("download_with_external_app", false);
3914 // Apply the proxy through Orbot settings.
3915 applyProxyThroughOrbot(false);
3917 // Set Do Not Track status.
3918 if (doNotTrackEnabled) {
3919 customHeaders.put("DNT", "1");
3921 customHeaders.remove("DNT");
3924 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3925 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3926 if (hideSystemBarsOnFullscreen) { // Hide everything.
3927 // Remove the translucent navigation setting if it is currently flagged.
3928 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3930 // Remove the translucent status bar overlay.
3931 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3933 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3934 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3936 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3937 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3938 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3940 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3941 } else { // Hide everything except the status and navigation bars.
3942 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3943 rootCoordinatorLayout.setSystemUiVisibility(0);
3945 // Add the translucent status flag if it is unset.
3946 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3948 if (translucentNavigationBarOnFullscreen) {
3949 // Set the navigation bar to be translucent.
3950 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3952 // Set the navigation bar to be black.
3953 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3956 } else { // Privacy Browser is not in full screen browsing mode.
3957 // Reset the full screen tracker, which could be true if Privacy Browser was in full screen mode before entering settings and full screen browsing was disabled.
3958 inFullScreenBrowsingMode = false;
3960 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3961 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3965 // Show the `BannerAd` in the free flavor.
3966 if (BuildConfig.FLAVOR.contentEquals("free")) {
3967 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3968 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3971 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3972 rootCoordinatorLayout.setSystemUiVisibility(0);
3974 // Remove the translucent navigation bar flag if it is set.
3975 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3977 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3978 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3980 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3981 rootCoordinatorLayout.setFitsSystemWindows(true);
3985 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3986 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3987 @SuppressWarnings("deprecation")
3988 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3989 // Parse the URL into a URI.
3990 Uri uri = Uri.parse(url);
3992 // Extract the domain from `uri`.
3993 String hostName = uri.getHost();
3995 // Initialize `loadingNewDomainName`.
3996 boolean loadingNewDomainName;
3998 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3999 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
4000 //noinspection SimplifiableIfStatement
4001 if ((hostName == null) || (currentDomainName == null)) {
4002 loadingNewDomainName = true;
4003 } else { // Determine if `hostName` equals `currentDomainName`.
4004 loadingNewDomainName = !hostName.equals(currentDomainName);
4007 // Strings don't like to be null.
4008 if (hostName == null) {
4012 // 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.
4013 if (loadingNewDomainName) {
4014 // Set the new `hostname` as the `currentDomainName`.
4015 currentDomainName = hostName;
4017 // Reset `ignorePinnedSslCertificate`.
4018 ignorePinnedSslCertificate = false;
4020 // Reset the favorite icon if specified.
4021 if (resetFavoriteIcon) {
4022 favoriteIconBitmap = favoriteIconDefaultBitmap;
4023 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
4026 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
4027 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
4029 // Get a full cursor from `domainsDatabaseHelper`.
4030 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
4032 // Initialize `domainSettingsSet`.
4033 Set<String> domainSettingsSet = new HashSet<>();
4035 // Get the domain name column index.
4036 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
4038 // Populate `domainSettingsSet`.
4039 for (int i = 0; i < domainNameCursor.getCount(); i++) {
4040 // Move `domainsCursor` to the current row.
4041 domainNameCursor.moveToPosition(i);
4043 // Store the domain name in `domainSettingsSet`.
4044 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
4047 // Close `domainNameCursor.
4048 domainNameCursor.close();
4050 // Initialize variables to track if domain settings will be applied and, if so, under which name.
4051 domainSettingsApplied = false;
4052 String domainNameInDatabase = null;
4054 // Check the hostname.
4055 if (domainSettingsSet.contains(hostName)) {
4056 domainSettingsApplied = true;
4057 domainNameInDatabase = hostName;
4060 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
4061 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
4062 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
4063 // Apply the domain settings.
4064 domainSettingsApplied = true;
4066 // Store the applied domain names as it appears in the database.
4067 domainNameInDatabase = "*." + hostName;
4070 // Strip out the lowest subdomain of of the host name.
4071 hostName = hostName.substring(hostName.indexOf(".") + 1);
4075 // Get a handle for the shared preference.
4076 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4078 // Store the general preference information.
4079 String defaultFontSizeString = sharedPreferences.getString("default_font_size", getString(R.string.font_size_default_value));
4080 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
4081 defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value));
4082 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
4083 nightMode = sharedPreferences.getBoolean("night_mode", false);
4084 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
4086 if (domainSettingsApplied) { // The url has custom domain settings.
4087 // Get a cursor for the current host and move it to the first position.
4088 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
4089 currentHostDomainSettingsCursor.moveToFirst();
4091 // Get the settings from the cursor.
4092 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
4093 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
4094 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
4095 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
4096 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
4097 // Form data can be removed once the minimum API >= 26.
4098 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
4099 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
4100 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
4101 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
4102 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
4103 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
4104 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
4105 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
4106 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
4107 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
4108 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
4109 int displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
4110 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
4111 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
4112 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
4113 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
4114 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
4115 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
4116 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
4118 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
4119 switch (nightModeInt) {
4120 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
4124 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
4129 // Store the domain JavaScript status. This is used by the options menu night mode toggle.
4130 domainSettingsJavaScriptEnabled = javaScriptEnabled;
4132 // Enable JavaScript if night mode is enabled.
4134 javaScriptEnabled = true;
4137 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
4138 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
4139 pinnedDomainSslStartDate = null;
4141 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
4144 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
4145 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
4146 pinnedDomainSslEndDate = null;
4148 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
4151 // Close `currentHostDomainSettingsCursor`.
4152 currentHostDomainSettingsCursor.close();
4154 // Apply the domain settings.
4155 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4156 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4157 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4159 // Apply the form data setting if the API < 26.
4160 if (Build.VERSION.SDK_INT < 26) {
4161 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4164 // Apply the font size.
4165 if (fontSize == 0) { // Apply the default font size.
4166 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4167 } else { // Apply the specified font size.
4168 mainWebView.getSettings().setTextZoom(fontSize);
4171 // Set third-party cookies status if API >= 21.
4172 if (Build.VERSION.SDK_INT >= 21) {
4173 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4176 // 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.
4177 // <https://redmine.stoutner.com/issues/160>
4178 if (!urlIsLoading) {
4179 // Set the user agent.
4180 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4181 // Get the array position of the default user agent name.
4182 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4184 // Set the user agent according to the system default.
4185 switch (defaultUserAgentArrayPosition) {
4186 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4187 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4188 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4191 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4192 // Set the user agent to `""`, which uses the default value.
4193 mainWebView.getSettings().setUserAgentString("");
4196 case SETTINGS_CUSTOM_USER_AGENT:
4197 // Set the custom user agent.
4198 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4202 // Get the user agent string from the user agent data array
4203 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4205 } else { // Set the user agent according to the stored name.
4206 // Get the array position of the user agent name.
4207 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4209 switch (userAgentArrayPosition) {
4210 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4211 mainWebView.getSettings().setUserAgentString(userAgentName);
4214 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4215 // Set the user agent to `""`, which uses the default value.
4216 mainWebView.getSettings().setUserAgentString("");
4220 // Get the user agent string from the user agent data array.
4221 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4225 // Set swipe to refresh.
4226 switch (swipeToRefreshInt) {
4227 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
4228 // Set swipe to refresh according to the default.
4229 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4232 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
4233 // Enable swipe to refresh.
4234 swipeRefreshLayout.setEnabled(true);
4237 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
4238 // Disable swipe to refresh.
4239 swipeRefreshLayout.setEnabled(false);
4242 // Store the applied user agent string, which is used in the View Source activity.
4243 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4246 // Set the loading of webpage images.
4247 switch (displayWebpageImagesInt) {
4248 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4249 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4252 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4253 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4256 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4257 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4261 // 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.
4263 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4265 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4267 } else { // The new URL does not have custom domain settings. Load the defaults.
4268 // Store the values from `sharedPreferences` in variables.
4269 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
4270 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
4271 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
4272 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
4273 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false); // Form data can be removed once the minimum API >= 26.
4274 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
4275 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
4276 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
4277 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
4278 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
4279 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
4281 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4283 javaScriptEnabled = true;
4286 // Apply the default settings.
4287 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4288 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4289 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4290 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4291 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4293 // Apply the form data setting if the API < 26.
4294 if (Build.VERSION.SDK_INT < 26) {
4295 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4298 // Reset the pinned SSL certificate information.
4299 domainSettingsDatabaseId = -1;
4300 pinnedDomainSslCertificate = false;
4301 pinnedDomainSslIssuedToCNameString = "";
4302 pinnedDomainSslIssuedToONameString = "";
4303 pinnedDomainSslIssuedToUNameString = "";
4304 pinnedDomainSslIssuedByCNameString = "";
4305 pinnedDomainSslIssuedByONameString = "";
4306 pinnedDomainSslIssuedByUNameString = "";
4307 pinnedDomainSslStartDate = null;
4308 pinnedDomainSslEndDate = null;
4310 // Set third-party cookies status if API >= 21.
4311 if (Build.VERSION.SDK_INT >= 21) {
4312 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4315 // 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.
4316 // <https://redmine.stoutner.com/issues/160>
4317 if (!urlIsLoading) {
4318 // Get the array position of the user agent name.
4319 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4321 // Set the user agent.
4322 switch (userAgentArrayPosition) {
4323 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4324 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4325 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4328 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4329 // Set the user agent to `""`, which uses the default value.
4330 mainWebView.getSettings().setUserAgentString("");
4333 case SETTINGS_CUSTOM_USER_AGENT:
4334 // Set the custom user agent.
4335 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4339 // Get the user agent string from the user agent data array
4340 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4343 // Store the applied user agent string, which is used in the View Source activity.
4344 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4347 // Set the loading of webpage images.
4348 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4350 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4351 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4354 // Close the domains database helper.
4355 domainsDatabaseHelper.close();
4357 // Update the privacy icons, but only if `mainMenu` has already been populated.
4358 if (mainMenu != null) {
4359 updatePrivacyIcons(true);
4363 // Reload the website if returning from the Domains activity.
4364 if (reloadWebsite) {
4365 mainWebView.reload();
4369 private void applyProxyThroughOrbot(boolean reloadWebsite) {
4370 // Get a handle for the shared preferences.
4371 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4373 // Get the search preferences.
4374 String homepageString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
4375 String torHomepageString = sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value));
4376 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
4377 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
4378 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
4379 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
4381 // Set the homepage, search, and proxy options.
4382 if (proxyThroughOrbot) { // Set the Tor options.
4383 // Set `torHomepageString` as `homepage`.
4384 homepage = torHomepageString;
4386 // If formattedUrlString is null assign the homepage to it.
4387 if (formattedUrlString == null) {
4388 formattedUrlString = homepage;
4391 // Set the search URL.
4392 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
4393 searchURL = torSearchCustomUrlString;
4394 } else { // Use the string from the pre-built list.
4395 searchURL = torSearchString;
4398 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
4399 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
4401 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
4403 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
4405 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
4408 // Check to see if Orbot is ready.
4409 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4410 // Set `waitingForOrbot`.
4411 waitingForOrbot = true;
4413 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
4414 mainWebView.getSettings().setUseWideViewPort(false);
4416 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
4417 mainWebView.loadData(waitingForOrbotHtmlString, "text/html", null);
4418 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
4419 // Reload the website.
4420 mainWebView.reload();
4422 } else { // Set the non-Tor options.
4423 // Set `homepageString` as `homepage`.
4424 homepage = homepageString;
4426 // If formattedUrlString is null assign the homepage to it.
4427 if (formattedUrlString == null) {
4428 formattedUrlString = homepage;
4431 // Set the search URL.
4432 if (searchString.equals("Custom URL")) { // Get the custom URL string.
4433 searchURL = searchCustomUrlString;
4434 } else { // Use the string from the pre-built list.
4435 searchURL = searchString;
4438 // Reset the proxy to default. The host is `""` and the port is `"0"`.
4439 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
4441 // Set the default `appBar` background. `this` refers to the context.
4443 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
4445 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
4448 // Reset `waitingForOrbot.
4449 waitingForOrbot = false;
4451 // Reload the website if requested.
4452 if (reloadWebsite) {
4453 mainWebView.reload();
4458 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4459 // Get handles for the menu items.
4460 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4461 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4462 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4463 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4465 // Update the privacy icon.
4466 if (javaScriptEnabled) { // JavaScript is enabled.
4467 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4468 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4469 privacyMenuItem.setIcon(R.drawable.warning);
4470 } else { // All the dangerous features are disabled.
4471 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4474 // Update the first-party cookies icon.
4475 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4476 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4477 } else { // First-party cookies are disabled.
4479 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4481 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4485 // Update the DOM storage icon.
4486 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4487 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4488 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4490 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4492 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4494 } else { // JavaScript is disabled, so DOM storage is ghosted.
4496 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4498 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4502 // Update the refresh icon.
4504 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4506 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4509 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4510 if (runInvalidateOptionsMenu) {
4511 invalidateOptionsMenu();
4515 private void openUrlWithExternalApp(String url) {
4516 // Create a download intent. Not specifying the action type will display the maximum number of options.
4517 Intent downloadIntent = new Intent();
4519 // Set the URI and the mime type. `"*/*"` will display the maximum number of options.
4520 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
4522 // Flag the intent to open in a new task.
4523 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4525 // Show the chooser.
4526 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4529 private void highlightUrlText() {
4530 String urlString = urlTextBox.getText().toString();
4532 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4533 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4534 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4535 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4538 // Get the index of the `/` immediately after the domain name.
4539 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4541 // De-emphasize the text after the domain name.
4542 if (endOfDomainName > 0) {
4543 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4547 private void loadBookmarksFolder() {
4548 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4549 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4551 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4552 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4554 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4555 // Inflate the individual item layout. `false` does not attach it to the root.
4556 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4560 public void bindView(View view, Context context, Cursor cursor) {
4561 // Get handles for the views.
4562 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4563 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4565 // Get the favorite icon byte array from the cursor.
4566 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4568 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4569 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4571 // Display the bitmap in `bookmarkFavoriteIcon`.
4572 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4574 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4575 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4576 bookmarkNameTextView.setText(bookmarkNameString);
4578 // Make the font bold for folders.
4579 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4580 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4581 } else { // Reset the font to default for normal bookmarks.
4582 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4587 // Populate the `ListView` with the adapter.
4588 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4590 // Set the bookmarks drawer title.
4591 if (currentBookmarksFolder.isEmpty()) {
4592 bookmarksTitleTextView.setText(R.string.bookmarks);
4594 bookmarksTitleTextView.setText(currentBookmarksFolder);