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 and the WebView. This removes any text selection markers and context menues, which otherwise draw above the open drawers.
926 urlTextBox.clearFocus();
927 mainWebView.clearFocus();
932 // drawerToggle creates the hamburger icon at the start of the AppBar.
933 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
935 // Get a handle for the progress bar.
936 final ProgressBar progressBar = findViewById(R.id.progress_bar);
938 mainWebView.setWebChromeClient(new WebChromeClient() {
939 // Update the progress bar when a page is loading.
941 public void onProgressChanged(WebView view, int progress) {
942 // Inject the night mode CSS if night mode is enabled.
944 // `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
945 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
946 // `border: none` removes all borders, which can also be used to underline text.
947 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
948 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
949 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
950 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
951 // Initialize a handler to display `mainWebView`.
952 Handler displayWebViewHandler = new Handler();
954 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
955 Runnable displayWebViewRunnable = () -> {
956 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
957 if (progressBar.getVisibility() == View.GONE) {
958 mainWebView.setVisibility(View.VISIBLE);
962 // Displaying of `mainWebView` after 500 milliseconds.
963 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
967 // Update the progress bar.
968 progressBar.setProgress(progress);
970 // Set the visibility of the progress bar.
971 if (progress < 100) {
972 // Show the progress bar.
973 progressBar.setVisibility(View.VISIBLE);
975 // Hide the progress bar.
976 progressBar.setVisibility(View.GONE);
978 // Display `mainWebView` if night mode is disabled.
979 // 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
980 // currently enabled.
982 mainWebView.setVisibility(View.VISIBLE);
985 //Stop the swipe to refresh indicator if it is running
986 swipeRefreshLayout.setRefreshing(false);
990 // Set the favorite icon when it changes.
992 public void onReceivedIcon(WebView view, Bitmap icon) {
993 // Only update the favorite icon if the website has finished loading.
994 if (progressBar.getVisibility() == View.GONE) {
995 // Save a copy of the favorite icon.
996 favoriteIconBitmap = icon;
998 // Place the favorite icon in the appBar.
999 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1003 // Save a copy of the title when it changes.
1005 public void onReceivedTitle(WebView view, String title) {
1006 // Save a copy of the title.
1007 webViewTitle = title;
1010 // Enter full screen video.
1012 public void onShowCustomView(View view, CustomViewCallback callback) {
1013 // Set the full screen video flag.
1014 displayingFullScreenVideo = true;
1016 // Pause the ad if this is the free flavor.
1017 if (BuildConfig.FLAVOR.contentEquals("free")) {
1018 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1019 AdHelper.pauseAd(findViewById(R.id.adview));
1022 // Remove the translucent overlays.
1023 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1025 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1026 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1028 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1029 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1030 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1032 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1034 // Set `rootCoordinatorLayout` to fill the entire screen.
1035 rootCoordinatorLayout.setFitsSystemWindows(false);
1037 // Disable the sliding drawers.
1038 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1040 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1041 fullScreenVideoFrameLayout.addView(view);
1042 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1045 // Exit full screen video.
1047 public void onHideCustomView() {
1048 // Unset the full screen video flag.
1049 displayingFullScreenVideo = false;
1051 // Hide `fullScreenVideoFrameLayout`.
1052 fullScreenVideoFrameLayout.removeAllViews();
1053 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1055 // Enable the sliding drawers.
1056 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1058 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1059 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1060 if (hideSystemBarsOnFullscreen) { // Hide everything.
1061 // Remove the translucent navigation setting if it is currently flagged.
1062 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1064 // Remove the translucent status bar overlay.
1065 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1067 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1068 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1070 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1071 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1072 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1074 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1075 } else { // Hide everything except the status and navigation bars.
1076 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1077 rootCoordinatorLayout.setSystemUiVisibility(0);
1079 // Add the translucent status flag if it is unset.
1080 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1082 if (translucentNavigationBarOnFullscreen) {
1083 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1084 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1086 // Set the navigation bar to be black.
1087 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1090 } else { // Switch to normal viewing mode.
1091 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1092 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1096 // Show the `BannerAd` in the free flavor.
1097 if (BuildConfig.FLAVOR.contentEquals("free")) {
1098 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1099 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
1102 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1103 rootCoordinatorLayout.setSystemUiVisibility(0);
1105 // Remove the translucent navigation bar flag if it is set.
1106 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1108 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1109 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1111 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1112 rootCoordinatorLayout.setFitsSystemWindows(true);
1115 // Show the ad if this is the free flavor.
1116 if (BuildConfig.FLAVOR.contentEquals("free")) {
1117 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1118 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
1124 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1125 // Show the file chooser if the device is running API >= 21.
1126 if (Build.VERSION.SDK_INT >= 21) {
1127 // Store the file path callback.
1128 fileChooserCallback = filePathCallback;
1130 // Create an intent to open a chooser based ont the file chooser parameters.
1131 Intent fileChooserIntent = fileChooserParams.createIntent();
1133 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1134 startActivityForResult(fileChooserIntent, 0);
1140 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1141 registerForContextMenu(mainWebView);
1143 // Allow the downloading of files.
1144 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1145 // Check if the download should be processed by an external app.
1146 if (downloadWithExternalApp) { // Download with an external app.
1147 openUrlWithExternalApp(url);
1148 } else { // Download with Android's download manager.
1149 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1150 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
1151 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1153 // Store the variables for future use by `onRequestPermissionsResult()`.
1155 downloadContentDisposition = contentDisposition;
1156 downloadContentLength = contentLength;
1158 // Show a dialog if the user has previously denied the permission.
1159 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1160 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1161 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1163 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1164 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1165 } else { // Show the permission request directly.
1166 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1167 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1169 } else { // The storage permission has already been granted.
1170 // Get a handle for the download file alert dialog.
1171 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1173 // Show the download file alert dialog.
1174 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1179 // Allow pinch to zoom.
1180 mainWebView.getSettings().setBuiltInZoomControls(true);
1182 // Hide zoom controls.
1183 mainWebView.getSettings().setDisplayZoomControls(false);
1185 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1186 mainWebView.getSettings().setUseWideViewPort(true);
1188 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1189 mainWebView.getSettings().setLoadWithOverviewMode(true);
1191 // Explicitly disable geolocation.
1192 mainWebView.getSettings().setGeolocationEnabled(false);
1194 // Initialize cookieManager.
1195 cookieManager = CookieManager.getInstance();
1197 // 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).
1198 customHeaders.put("X-Requested-With", "");
1200 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1201 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1203 // Get the intent that started the app.
1204 final Intent launchingIntent = getIntent();
1206 // Extract the launching intent data as `launchingIntentUriData`.
1207 final Uri launchingIntentUriData = launchingIntent.getData();
1209 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1210 if (launchingIntentUriData != null) {
1211 formattedUrlString = launchingIntentUriData.toString();
1214 // Get a handle for the `Runtime`.
1215 privacyBrowserRuntime = Runtime.getRuntime();
1217 // Store the application's private data directory.
1218 privateDataDirectoryString = getApplicationInfo().dataDir;
1219 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1221 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1222 inFullScreenBrowsingMode = false;
1224 // Initialize the privacy settings variables.
1225 javaScriptEnabled = false;
1226 firstPartyCookiesEnabled = false;
1227 thirdPartyCookiesEnabled = false;
1228 domStorageEnabled = false;
1229 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1232 // Store the default user agent.
1233 webViewDefaultUserAgent = mainWebView.getSettings().getUserAgentString();
1235 // Initialize the WebView title.
1236 webViewTitle = getString(R.string.no_title);
1238 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1239 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1240 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1241 assert favoriteIconBitmapDrawable != null;
1242 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1244 // If the favorite icon is null, load the default.
1245 if (favoriteIconBitmap == null) {
1246 favoriteIconBitmap = favoriteIconDefaultBitmap;
1249 // Initialize the user agent array adapter and string array.
1250 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
1251 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1253 // Apply the app settings from the shared preferences.
1256 // Instantiate the block list helper.
1257 BlockListHelper blockListHelper = new BlockListHelper();
1259 // Initialize the list of resource requests.
1260 resourceRequests = new ArrayList<>();
1262 // Parse the block lists.
1263 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1264 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1265 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1266 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1267 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1269 // Store the list versions.
1270 easyListVersion = easyList.get(0).get(0)[0];
1271 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1272 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1273 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1274 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1276 // Get a handle for the activity. This is used to update the requests counter while the navigation menu is open.
1277 Activity activity = this;
1279 mainWebView.setWebViewClient(new WebViewClient() {
1280 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1281 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1282 @SuppressWarnings("deprecation")
1284 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1285 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1286 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1287 formattedUrlString = "";
1289 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1290 boolean userAgentChanged = applyDomainSettings(url, true, false);
1292 // Check if the user agent has changed.
1293 if (userAgentChanged) {
1294 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
1295 mainWebView.loadUrl(url, customHeaders);
1297 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
1300 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1303 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1304 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1305 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1307 // Parse the url and set it as the data for the intent.
1308 emailIntent.setData(Uri.parse(url));
1310 // Open the email program in a new task instead of as part of Privacy Browser.
1311 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1314 startActivity(emailIntent);
1316 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1318 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1319 // Open the dialer and load the phone number, but wait for the user to place the call.
1320 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1322 // Add the phone number to the intent.
1323 dialIntent.setData(Uri.parse(url));
1325 // Open the dialer in a new task instead of as part of Privacy Browser.
1326 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1329 startActivity(dialIntent);
1331 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1333 } else { // Load a system chooser to select an app that can handle the URL.
1334 // Open an app that can handle the URL.
1335 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1337 // Add the URL to the intent.
1338 genericIntent.setData(Uri.parse(url));
1340 // List all apps that can handle the URL instead of just opening the first one.
1341 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1343 // Open the app in a new task instead of as part of Privacy Browser.
1344 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1346 // Start the app or display a snackbar if no app is available to handle the URL.
1348 startActivity(genericIntent);
1349 } catch (ActivityNotFoundException exception) {
1350 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1353 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1358 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1359 @SuppressWarnings("deprecation")
1361 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1362 // Create an empty web resource response to be used if the resource request is blocked.
1363 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1365 // Reset the whitelist results tracker.
1366 whiteListResultStringArray = null;
1368 // Initialize the third party request tracker.
1369 boolean isThirdPartyRequest = false;
1371 // Initialize the current domain string.
1372 String currentDomain = "";
1374 // Nobody is happy when comparing null strings.
1375 if (!(formattedUrlString == null) && !(url == null)) {
1376 // Get the domain strings to URIs.
1377 Uri currentDomainUri = Uri.parse(formattedUrlString);
1378 Uri requestDomainUri = Uri.parse(url);
1380 // Get the domain host names.
1381 String currentBaseDomain = currentDomainUri.getHost();
1382 String requestBaseDomain = requestDomainUri.getHost();
1384 // Update the current domain variable.
1385 currentDomain = currentBaseDomain;
1387 // Only compare the current base domain and the request base domain if neither is null.
1388 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1389 // Determine the current base domain.
1390 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1391 // Remove the first subdomain.
1392 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1395 // Determine the request base domain.
1396 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1397 // Remove the first subdomain.
1398 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1401 // Update the third party request tracker.
1402 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1406 // Block third-party requests if enabled.
1407 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1408 // Increment the blocked requests counters.
1410 thirdPartyBlockedRequests++;
1412 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1413 activity.runOnUiThread(() -> {
1414 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1415 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1416 blockAllThirdPartyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1419 // Add the request to the log.
1420 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1422 // Return an empty web resource response.
1423 return emptyWebResourceResponse;
1426 // Check UltraPrivacy if it is enabled.
1427 if (ultraPrivacyEnabled) {
1428 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1429 // Increment the blocked requests counters.
1431 ultraPrivacyBlockedRequests++;
1433 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1434 activity.runOnUiThread(() -> {
1435 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1436 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1437 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1440 // The resource request was blocked. Return an empty web resource response.
1441 return emptyWebResourceResponse;
1444 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1445 if (whiteListResultStringArray != null) {
1446 // Add a whitelist entry to the resource requests array.
1447 resourceRequests.add(whiteListResultStringArray);
1449 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1454 // Check EasyList if it is enabled.
1455 if (easyListEnabled) {
1456 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1457 // Increment the blocked requests counters.
1459 easyListBlockedRequests++;
1461 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1462 activity.runOnUiThread(() -> {
1463 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1464 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1465 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1468 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1469 whiteListResultStringArray = null;
1471 // The resource request was blocked. Return an empty web resource response.
1472 return emptyWebResourceResponse;
1476 // Check EasyPrivacy if it is enabled.
1477 if (easyPrivacyEnabled) {
1478 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1479 // Increment the blocked requests counters.
1481 easyPrivacyBlockedRequests++;
1483 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1484 activity.runOnUiThread(() -> {
1485 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1486 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1487 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1490 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1491 whiteListResultStringArray = null;
1493 // The resource request was blocked. Return an empty web resource response.
1494 return emptyWebResourceResponse;
1498 // Check Fanboy’s Annoyance List if it is enabled.
1499 if (fanboysAnnoyanceListEnabled) {
1500 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1501 // Increment the blocked requests counters.
1503 fanboysAnnoyanceListBlockedRequests++;
1505 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1506 activity.runOnUiThread(() -> {
1507 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1508 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1509 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1512 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1513 whiteListResultStringArray = null;
1515 // The resource request was blocked. Return an empty web resource response.
1516 return emptyWebResourceResponse;
1518 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1519 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1520 // Increment the blocked requests counters.
1522 fanboysSocialBlockingListBlockedRequests++;
1524 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1525 activity.runOnUiThread(() -> {
1526 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1527 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1528 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1531 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1532 whiteListResultStringArray = null;
1534 // The resource request was blocked. Return an empty web resource response.
1535 return emptyWebResourceResponse;
1539 // Add the request to the log because it hasn't been processed by any of the previous checks.
1540 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1541 resourceRequests.add(whiteListResultStringArray);
1542 } else { // The request didn't match any blocklist entry. Log it as a default request.
1543 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1546 // The resource request has not been blocked. `return null` loads the requested resource.
1550 // Handle HTTP authentication requests.
1552 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1553 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1554 httpAuthHandler = handler;
1556 // Display the HTTP authentication dialog.
1557 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1558 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1561 // Update the URL in urlTextBox when the page starts to load.
1563 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1564 // Reset the list of resource requests.
1565 resourceRequests.clear();
1567 // Initialize the counters for requests blocked by each blocklist.
1568 blockedRequests = 0;
1569 easyListBlockedRequests = 0;
1570 easyPrivacyBlockedRequests = 0;
1571 fanboysAnnoyanceListBlockedRequests = 0;
1572 fanboysSocialBlockingListBlockedRequests = 0;
1573 ultraPrivacyBlockedRequests = 0;
1574 thirdPartyBlockedRequests = 0;
1576 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1578 mainWebView.setVisibility(View.INVISIBLE);
1581 // Hide the keyboard. `0` indicates no additional flags.
1582 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1584 // Check to see if Privacy Browser is waiting on Orbot.
1585 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1586 // 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.
1587 formattedUrlString = url;
1589 // Display the formatted URL text.
1590 urlTextBox.setText(formattedUrlString);
1592 // Apply text highlighting to `urlTextBox`.
1595 // Apply any custom domain settings if the URL was loaded by navigating history.
1596 if (navigatingHistory) {
1597 // Apply the domain settings.
1598 boolean userAgentChanged = applyDomainSettings(url, true, false);
1600 // Reset `navigatingHistory`.
1601 navigatingHistory = false;
1603 // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
1604 if (userAgentChanged) {
1605 loadUrl(formattedUrlString);
1609 // 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.
1610 urlIsLoading = true;
1612 // Replace Refresh with Stop if the menu item has been created. (The WebView typically begins loading before the menu items are instantiated.)
1613 if (refreshMenuItem != null) {
1615 refreshMenuItem.setTitle(R.string.stop);
1617 // If the icon is displayed in the AppBar, set it according to the theme.
1618 if (displayAdditionalAppBarIcons) {
1620 refreshMenuItem.setIcon(R.drawable.close_dark);
1622 refreshMenuItem.setIcon(R.drawable.close_light);
1629 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1631 public void onPageFinished(WebView view, String url) {
1632 // Reset the wide view port if it has been turned off by the waiting for Orbot message.
1633 if (!waitingForOrbot) {
1634 mainWebView.getSettings().setUseWideViewPort(true);
1637 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1638 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1639 cookieManager.flush();
1642 // Update the Refresh menu item if it has been created.
1643 if (refreshMenuItem != null) {
1644 // Reset the Refresh title.
1645 refreshMenuItem.setTitle(R.string.refresh);
1647 // If the icon is displayed in the AppBar, reset it according to the theme.
1648 if (displayAdditionalAppBarIcons) {
1650 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1652 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1657 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1658 urlIsLoading = false;
1660 // Clear the cache and history if Incognito Mode is enabled.
1661 if (incognitoModeEnabled) {
1662 // Clear the cache. `true` includes disk files.
1663 mainWebView.clearCache(true);
1665 // Clear the back/forward history.
1666 mainWebView.clearHistory();
1668 // Manually delete cache folders.
1670 // Delete the main cache directory.
1671 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1673 // Delete the secondary `Service Worker` cache directory.
1674 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1675 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1676 } catch (IOException e) {
1677 // Do nothing if an error is thrown.
1681 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1682 if (!waitingForOrbot) {
1683 // Check to see if `WebView` has set `url` to be `about:blank`.
1684 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1685 // Set `formattedUrlString` to `""`.
1686 formattedUrlString = "";
1688 urlTextBox.setText(formattedUrlString);
1690 // Request focus for `urlTextBox`.
1691 urlTextBox.requestFocus();
1693 // Display the keyboard.
1694 inputMethodManager.showSoftInput(urlTextBox, 0);
1696 // Apply the domain settings. This clears any settings from the previous domain.
1697 applyDomainSettings(formattedUrlString, true, false);
1698 } else { // `WebView` has loaded a webpage.
1699 // Set `formattedUrlString`.
1700 formattedUrlString = url;
1702 // Only update `urlTextBox` if the user is not typing in it.
1703 if (!urlTextBox.hasFocus()) {
1704 // Display the formatted URL text.
1705 urlTextBox.setText(formattedUrlString);
1707 // Apply text highlighting to `urlTextBox`.
1712 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1713 sslCertificate = mainWebView.getCertificate();
1715 // 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.
1716 // Also ignore if changes in the user agent causes an error while navigating history.
1717 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate && navigatingHistory) {
1718 // Initialize the current SSL certificate variables.
1719 String currentWebsiteIssuedToCName = "";
1720 String currentWebsiteIssuedToOName = "";
1721 String currentWebsiteIssuedToUName = "";
1722 String currentWebsiteIssuedByCName = "";
1723 String currentWebsiteIssuedByOName = "";
1724 String currentWebsiteIssuedByUName = "";
1725 Date currentWebsiteSslStartDate = null;
1726 Date currentWebsiteSslEndDate = null;
1729 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1730 if (sslCertificate != null) {
1731 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1732 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1733 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1734 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1735 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1736 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1737 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1738 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1741 // 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`.
1742 String currentWebsiteSslStartDateString = "";
1743 String currentWebsiteSslEndDateString = "";
1744 String pinnedDomainSslStartDateString = "";
1745 String pinnedDomainSslEndDateString = "";
1747 // Convert the `Dates` to `Strings` if they are not `null`.
1748 if (currentWebsiteSslStartDate != null) {
1749 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1752 if (currentWebsiteSslEndDate != null) {
1753 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1756 if (pinnedDomainSslStartDate != null) {
1757 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1760 if (pinnedDomainSslEndDate != null) {
1761 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1764 // Check to see if the pinned SSL certificate matches the current website certificate.
1765 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1766 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1767 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1768 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1769 // The pinned SSL certificate doesn't match the current domain certificate.
1770 //Display the pinned SSL certificate mismatch `AlertDialog`.
1771 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1772 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1778 // Handle SSL Certificate errors.
1780 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1781 // Get the current website SSL certificate.
1782 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1784 // Extract the individual pieces of information from the current website SSL certificate.
1785 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1786 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1787 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1788 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1789 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1790 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1791 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1792 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1794 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1795 if (pinnedDomainSslCertificate &&
1796 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1797 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1798 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1799 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1800 // An SSL certificate is pinned and matches the current domain certificate.
1801 // Proceed to the website without displaying an error.
1803 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1804 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1805 sslErrorHandler = handler;
1807 // Display the SSL error `AlertDialog`.
1808 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1809 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1814 // Load the website if not waiting for Orbot to connect.
1815 if (!waitingForOrbot) {
1816 loadUrl(formattedUrlString);
1821 protected void onNewIntent(Intent intent) {
1822 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1825 // Check to see if the intent contains a new URL.
1826 if (intent.getData() != null) {
1827 // Get the intent data.
1828 final Uri intentUriData = intent.getData();
1830 // Load the website.
1831 loadUrl(intentUriData.toString());
1833 // Close the navigation drawer if it is open.
1834 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1835 drawerLayout.closeDrawer(GravityCompat.START);
1838 // Close the bookmarks drawer if it is open.
1839 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1840 drawerLayout.closeDrawer(GravityCompat.END);
1843 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1844 mainWebView.requestFocus();
1849 public void onRestart() {
1850 // Run the default commands.
1853 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1854 if (proxyThroughOrbot) {
1855 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1856 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1858 // Send the intent to the Orbot package.
1859 orbotIntent.setPackage("org.torproject.android");
1862 sendBroadcast(orbotIntent);
1865 // Apply the app settings if returning from the Settings activity..
1866 if (reapplyAppSettingsOnRestart) {
1867 // Apply the app settings.
1870 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1871 if (reloadOnRestart) {
1872 // Reload `mainWebView`.
1873 mainWebView.reload();
1875 // Reset `reloadOnRestartBoolean`.
1876 reloadOnRestart = false;
1879 // Reset the return from settings flag.
1880 reapplyAppSettingsOnRestart = false;
1883 // Apply the domain settings if returning from the Domains activity.
1884 if (reapplyDomainSettingsOnRestart) {
1885 // Reapply the domain settings.
1886 applyDomainSettings(formattedUrlString, false, true);
1888 // Reset `reapplyDomainSettingsOnRestart`.
1889 reapplyDomainSettingsOnRestart = false;
1892 // Load the URL on restart to apply changes to night mode.
1893 if (loadUrlOnRestart) {
1894 // Load the current `formattedUrlString`.
1895 loadUrl(formattedUrlString);
1897 // Reset `loadUrlOnRestart.
1898 loadUrlOnRestart = false;
1901 // Update the bookmarks drawer if returning from the Bookmarks activity.
1902 if (restartFromBookmarksActivity) {
1903 // Close the bookmarks drawer.
1904 drawerLayout.closeDrawer(GravityCompat.END);
1906 // Reload the bookmarks drawer.
1907 loadBookmarksFolder();
1909 // Reset `restartFromBookmarksActivity`.
1910 restartFromBookmarksActivity = false;
1913 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1914 updatePrivacyIcons(true);
1917 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1919 public void onResume() {
1920 // Run the default commands.
1923 // Resume JavaScript (if enabled).
1924 mainWebView.resumeTimers();
1926 // Resume `mainWebView`.
1927 mainWebView.onResume();
1929 // Resume the adView for the free flavor.
1930 if (BuildConfig.FLAVOR.contentEquals("free")) {
1932 AdHelper.resumeAd(findViewById(R.id.adview));
1935 // Display a message to the user if waiting for Orbot.
1936 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1937 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
1938 mainWebView.getSettings().setUseWideViewPort(false);
1940 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1941 mainWebView.loadData(waitingForOrbotHtmlString, "text/html", null);
1944 if (displayingFullScreenVideo) {
1945 // Remove the translucent overlays.
1946 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1948 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1949 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1951 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1952 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1953 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1955 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1960 public void onPause() {
1961 // Run the default commands.
1964 // Pause `mainWebView`.
1965 mainWebView.onPause();
1967 // Stop all JavaScript.
1968 mainWebView.pauseTimers();
1970 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1971 if (BuildConfig.FLAVOR.contentEquals("free")) {
1973 AdHelper.pauseAd(findViewById(R.id.adview));
1978 public void onDestroy() {
1979 // Unregister the Orbot status broadcast receiver.
1980 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1982 // Close the bookmarks cursor and database.
1983 bookmarksCursor.close();
1984 bookmarksDatabaseHelper.close();
1986 // Run the default commands.
1991 public boolean onCreateOptionsMenu(Menu menu) {
1992 // Inflate the menu; this adds items to the action bar if it is present.
1993 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1995 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1998 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1999 updatePrivacyIcons(false);
2001 // Get handles for the menu items.
2002 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2003 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2004 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2005 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
2006 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
2007 refreshMenuItem = menu.findItem(R.id.refresh);
2008 blocklistsMenuItem = menu.findItem(R.id.blocklists);
2009 easyListMenuItem = menu.findItem(R.id.easylist);
2010 easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
2011 fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
2012 fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
2013 ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
2014 blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
2015 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
2017 // Only display third-party cookies if API >= 21
2018 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
2020 // Only display the form data menu items if the API < 26.
2021 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
2022 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
2024 // Only show Ad Consent if this is the free flavor.
2025 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
2027 // Get the shared preference values.
2028 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2030 // Get the status of the additional AppBar icons.
2031 displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
2033 // 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.
2034 if (displayAdditionalAppBarIcons) {
2035 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2036 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2037 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
2038 } else { //Do not display the additional icons.
2039 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2040 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2041 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2044 // Replace Refresh with Stop if a URL is already loading.
2047 refreshMenuItem.setTitle(R.string.stop);
2049 // If the icon is displayed in the AppBar, set it according to the theme.
2050 if (displayAdditionalAppBarIcons) {
2052 refreshMenuItem.setIcon(R.drawable.close_dark);
2054 refreshMenuItem.setIcon(R.drawable.close_light);
2063 public boolean onPrepareOptionsMenu(Menu menu) {
2064 // Get handles for the menu items.
2065 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2066 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2067 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2068 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2069 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
2070 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2071 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2072 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2073 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
2074 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2075 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
2076 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2077 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
2078 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
2080 // Set the text for the domain menu item.
2081 if (domainSettingsApplied) {
2082 addOrEditDomain.setTitle(R.string.edit_domain_settings);
2084 addOrEditDomain.setTitle(R.string.add_domain_settings);
2087 // Set the status of the menu item checkboxes.
2088 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2089 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2090 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2091 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
2092 easyListMenuItem.setChecked(easyListEnabled);
2093 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
2094 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
2095 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
2096 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
2097 blockAllThirdPartyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
2098 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
2099 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2100 nightModeMenuItem.setChecked(nightMode);
2101 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
2103 // Enable third-party cookies if first-party cookies are enabled.
2104 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2106 // Enable DOM Storage if JavaScript is enabled.
2107 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2109 // Enable Clear Cookies if there are any.
2110 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2112 // Get a count of the number of files in the Local Storage directory.
2113 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2114 int localStorageDirectoryNumberOfFiles = 0;
2115 if (localStorageDirectory.exists()) {
2116 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2119 // Get a count of the number of files in the IndexedDB directory.
2120 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2121 int indexedDBDirectoryNumberOfFiles = 0;
2122 if (indexedDBDirectory.exists()) {
2123 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2126 // Enable Clear DOM Storage if there is any.
2127 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2129 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
2130 if (Build.VERSION.SDK_INT < 26) {
2131 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2132 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2134 // Disable clear form data because it is not supported on current version of Android.
2135 clearFormDataMenuItem.setEnabled(false);
2138 // Enable Clear Data if any of the submenu items are enabled.
2139 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2141 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2142 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2144 // Initialize the display names for the blocklists with the number of blocked requests.
2145 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
2146 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2147 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2148 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2149 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2150 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2151 blockAllThirdPartyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2153 // Get the current user agent.
2154 String currentUserAgent = mainWebView.getSettings().getUserAgentString();
2156 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
2157 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
2158 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
2159 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
2160 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
2161 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
2162 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
2163 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
2164 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
2165 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
2166 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
2167 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
2168 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
2169 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
2170 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
2171 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
2172 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
2173 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
2174 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
2175 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
2176 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
2177 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
2178 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
2179 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
2180 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
2181 } else { // Custom user agent.
2182 menu.findItem(R.id.user_agent_custom).setChecked(true);
2185 // Initialize font size variables.
2186 int fontSize = mainWebView.getSettings().getTextZoom();
2187 String fontSizeTitle;
2188 MenuItem selectedFontSizeMenuItem;
2190 // Prepare the font size title and current size menu item.
2193 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2194 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2198 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2199 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2203 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2204 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2208 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2209 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2213 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2214 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2218 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2219 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2223 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2224 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2228 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2229 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2233 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2234 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2238 // Set the font size title and select the current size menu item.
2239 fontSizeMenuItem.setTitle(fontSizeTitle);
2240 selectedFontSizeMenuItem.setChecked(true);
2242 // Run all the other default commands.
2243 super.onPrepareOptionsMenu(menu);
2245 // Display the menu.
2250 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2251 @SuppressLint("SetJavaScriptEnabled")
2252 // removeAllCookies is deprecated, but it is required for API < 21.
2253 @SuppressWarnings("deprecation")
2254 public boolean onOptionsItemSelected(MenuItem menuItem) {
2255 // Get the selected menu item ID.
2256 int menuItemId = menuItem.getItemId();
2258 // Set the commands that relate to the menu entries.
2259 switch (menuItemId) {
2260 case R.id.toggle_javascript:
2261 // Switch the status of javaScriptEnabled.
2262 javaScriptEnabled = !javaScriptEnabled;
2264 // Apply the new JavaScript status.
2265 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2267 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2268 updatePrivacyIcons(true);
2270 // Display a `Snackbar`.
2271 if (javaScriptEnabled) { // JavaScrip is enabled.
2272 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2273 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2274 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2275 } else { // Privacy mode.
2276 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2279 // Reload the WebView.
2280 mainWebView.reload();
2283 case R.id.add_or_edit_domain:
2284 if (domainSettingsApplied) { // Edit the current domain settings.
2285 // Reapply the domain settings on returning to `MainWebViewActivity`.
2286 reapplyDomainSettingsOnRestart = true;
2287 currentDomainName = "";
2289 // Create an intent to launch the domains activity.
2290 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2292 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2293 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2294 domainsIntent.putExtra("closeOnBack", true);
2297 startActivity(domainsIntent);
2298 } else { // Add a new domain.
2299 // Apply the new domain settings on returning to `MainWebViewActivity`.
2300 reapplyDomainSettingsOnRestart = true;
2301 currentDomainName = "";
2303 // Get the current domain
2304 Uri currentUri = Uri.parse(formattedUrlString);
2305 String currentDomain = currentUri.getHost();
2307 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2308 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2310 // Create the domain and store the database ID.
2311 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2313 // Create an intent to launch the domains activity.
2314 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2316 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2317 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2318 domainsIntent.putExtra("closeOnBack", true);
2321 startActivity(domainsIntent);
2325 case R.id.toggle_first_party_cookies:
2326 // Switch the status of firstPartyCookiesEnabled.
2327 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2329 // Update the menu checkbox.
2330 menuItem.setChecked(firstPartyCookiesEnabled);
2332 // Apply the new cookie status.
2333 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2335 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2336 updatePrivacyIcons(true);
2338 // Display a `Snackbar`.
2339 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2340 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2341 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2342 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2343 } else { // Privacy mode.
2344 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2347 // Reload the WebView.
2348 mainWebView.reload();
2351 case R.id.toggle_third_party_cookies:
2352 if (Build.VERSION.SDK_INT >= 21) {
2353 // Switch the status of thirdPartyCookiesEnabled.
2354 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2356 // Update the menu checkbox.
2357 menuItem.setChecked(thirdPartyCookiesEnabled);
2359 // Apply the new cookie status.
2360 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2362 // Display a `Snackbar`.
2363 if (thirdPartyCookiesEnabled) {
2364 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2366 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2369 // Reload the WebView.
2370 mainWebView.reload();
2371 } // Else do nothing because SDK < 21.
2374 case R.id.toggle_dom_storage:
2375 // Switch the status of domStorageEnabled.
2376 domStorageEnabled = !domStorageEnabled;
2378 // Update the menu checkbox.
2379 menuItem.setChecked(domStorageEnabled);
2381 // Apply the new DOM Storage status.
2382 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2384 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2385 updatePrivacyIcons(true);
2387 // Display a `Snackbar`.
2388 if (domStorageEnabled) {
2389 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2391 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2394 // Reload the WebView.
2395 mainWebView.reload();
2398 // Form data can be removed once the minimum API >= 26.
2399 case R.id.toggle_save_form_data:
2400 // Switch the status of saveFormDataEnabled.
2401 saveFormDataEnabled = !saveFormDataEnabled;
2403 // Update the menu checkbox.
2404 menuItem.setChecked(saveFormDataEnabled);
2406 // Apply the new form data status.
2407 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2409 // Display a `Snackbar`.
2410 if (saveFormDataEnabled) {
2411 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2413 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2416 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2417 updatePrivacyIcons(true);
2419 // Reload the WebView.
2420 mainWebView.reload();
2423 case R.id.clear_cookies:
2424 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2425 .setAction(R.string.undo, v -> {
2426 // Do nothing because everything will be handled by `onDismissed()` below.
2428 .addCallback(new Snackbar.Callback() {
2430 public void onDismissed(Snackbar snackbar, int event) {
2432 // The user pushed the `Undo` button.
2433 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2437 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2439 // `cookieManager.removeAllCookie()` varies by SDK.
2440 if (Build.VERSION.SDK_INT < 21) {
2441 cookieManager.removeAllCookie();
2443 // `null` indicates no callback.
2444 cookieManager.removeAllCookies(null);
2452 case R.id.clear_dom_storage:
2453 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2454 .setAction(R.string.undo, v -> {
2455 // Do nothing because everything will be handled by `onDismissed()` below.
2457 .addCallback(new Snackbar.Callback() {
2459 public void onDismissed(Snackbar snackbar, int event) {
2461 // The user pushed the `Undo` button.
2462 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2466 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2468 // Delete the DOM Storage.
2469 WebStorage webStorage = WebStorage.getInstance();
2470 webStorage.deleteAllData();
2472 // Initialize a handler to manually delete the DOM storage files and directories.
2473 Handler deleteDomStorageHandler = new Handler();
2475 // Setup a runnable to manually delete the DOM storage files and directories.
2476 Runnable deleteDomStorageRunnable = () -> {
2478 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2479 privacyBrowserRuntime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2481 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2482 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2483 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2484 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2485 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2486 } catch (IOException e) {
2487 // Do nothing if an error is thrown.
2491 // Manually delete the DOM storage files after 200 milliseconds.
2492 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
2499 // Form data can be remove once the minimum API >= 26.
2500 case R.id.clear_form_data:
2501 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2502 .setAction(R.string.undo, v -> {
2503 // Do nothing because everything will be handled by `onDismissed()` below.
2505 .addCallback(new Snackbar.Callback() {
2507 public void onDismissed(Snackbar snackbar, int event) {
2509 // The user pushed the `Undo` button.
2510 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2514 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2516 // Delete the form data.
2517 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2518 mainWebViewDatabase.clearFormData();
2526 // Toggle the EasyList status.
2527 easyListEnabled = !easyListEnabled;
2529 // Update the menu checkbox.
2530 menuItem.setChecked(easyListEnabled);
2532 // Reload the main WebView.
2533 mainWebView.reload();
2536 case R.id.easyprivacy:
2537 // Toggle the EasyPrivacy status.
2538 easyPrivacyEnabled = !easyPrivacyEnabled;
2540 // Update the menu checkbox.
2541 menuItem.setChecked(easyPrivacyEnabled);
2543 // Reload the main WebView.
2544 mainWebView.reload();
2547 case R.id.fanboys_annoyance_list:
2548 // Toggle Fanboy's Annoyance List status.
2549 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2551 // Update the menu checkbox.
2552 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2554 // Update the staus of Fanboy's Social Blocking List.
2555 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2556 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2558 // Reload the main WebView.
2559 mainWebView.reload();
2562 case R.id.fanboys_social_blocking_list:
2563 // Toggle Fanboy's Social Blocking List status.
2564 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2566 // Update the menu checkbox.
2567 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2569 // Reload the main WebView.
2570 mainWebView.reload();
2573 case R.id.ultraprivacy:
2574 // Toggle the UltraPrivacy status.
2575 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2577 // Update the menu checkbox.
2578 menuItem.setChecked(ultraPrivacyEnabled);
2580 // Reload the main WebView.
2581 mainWebView.reload();
2584 case R.id.block_all_third_party_requests:
2585 //Toggle the third-party requests blocker status.
2586 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2588 // Update the menu checkbox.
2589 menuItem.setChecked(blockAllThirdPartyRequests);
2591 // Reload the main WebView.
2592 mainWebView.reload();
2595 case R.id.user_agent_privacy_browser:
2596 // Update the user agent.
2597 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
2599 // Reload the WebView.
2600 mainWebView.reload();
2603 case R.id.user_agent_webview_default:
2604 // Update the user agent.
2605 mainWebView.getSettings().setUserAgentString("");
2607 // Reload the WebView.
2608 mainWebView.reload();
2611 case R.id.user_agent_firefox_on_android:
2612 // Update the user agent.
2613 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
2615 // Reload the WebView.
2616 mainWebView.reload();
2619 case R.id.user_agent_chrome_on_android:
2620 // Update the user agent.
2621 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
2623 // Reload the WebView.
2624 mainWebView.reload();
2627 case R.id.user_agent_safari_on_ios:
2628 // Update the user agent.
2629 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
2631 // Reload the WebView.
2632 mainWebView.reload();
2635 case R.id.user_agent_firefox_on_linux:
2636 // Update the user agent.
2637 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
2639 // Reload the WebView.
2640 mainWebView.reload();
2643 case R.id.user_agent_chromium_on_linux:
2644 // Update the user agent.
2645 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
2647 // Reload the WebView.
2648 mainWebView.reload();
2651 case R.id.user_agent_firefox_on_windows:
2652 // Update the user agent.
2653 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
2655 // Reload the WebView.
2656 mainWebView.reload();
2659 case R.id.user_agent_chrome_on_windows:
2660 // Update the user agent.
2661 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
2663 // Reload the WebView.
2664 mainWebView.reload();
2667 case R.id.user_agent_edge_on_windows:
2668 // Update the user agent.
2669 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
2671 // Reload the WebView.
2672 mainWebView.reload();
2675 case R.id.user_agent_internet_explorer_on_windows:
2676 // Update the user agent.
2677 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
2679 // Reload the WebView.
2680 mainWebView.reload();
2683 case R.id.user_agent_safari_on_macos:
2684 // Update the user agent.
2685 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
2687 // Reload the WebView.
2688 mainWebView.reload();
2691 case R.id.user_agent_custom:
2692 // Update the user agent.
2693 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2695 // Reload the WebView.
2696 mainWebView.reload();
2699 case R.id.font_size_twenty_five_percent:
2700 mainWebView.getSettings().setTextZoom(25);
2703 case R.id.font_size_fifty_percent:
2704 mainWebView.getSettings().setTextZoom(50);
2707 case R.id.font_size_seventy_five_percent:
2708 mainWebView.getSettings().setTextZoom(75);
2711 case R.id.font_size_one_hundred_percent:
2712 mainWebView.getSettings().setTextZoom(100);
2715 case R.id.font_size_one_hundred_twenty_five_percent:
2716 mainWebView.getSettings().setTextZoom(125);
2719 case R.id.font_size_one_hundred_fifty_percent:
2720 mainWebView.getSettings().setTextZoom(150);
2723 case R.id.font_size_one_hundred_seventy_five_percent:
2724 mainWebView.getSettings().setTextZoom(175);
2727 case R.id.font_size_two_hundred_percent:
2728 mainWebView.getSettings().setTextZoom(200);
2731 case R.id.swipe_to_refresh:
2732 // Toggle swipe to refresh.
2733 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2736 case R.id.display_images:
2737 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2738 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2739 mainWebView.reload();
2740 } else { // Images are not currently loaded automatically.
2741 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2745 case R.id.night_mode:
2746 // Toggle night mode.
2747 nightMode = !nightMode;
2749 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
2750 if (nightMode) { // Night mode is enabled. Enable JavaScript.
2751 // Update the global variable.
2752 javaScriptEnabled = true;
2753 } else if (domainSettingsApplied) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
2754 // Get the JavaScript preference that was stored the last time domain settings were loaded.
2755 javaScriptEnabled = domainSettingsJavaScriptEnabled;
2756 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
2757 // Get a handle for the shared preference.
2758 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2760 // Get the JavaScript preference.
2761 javaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
2764 // Apply the JavaScript setting to the WebView.
2765 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2767 // Update the privacy icons.
2768 updatePrivacyIcons(false);
2770 // Reload the website.
2771 mainWebView.reload();
2775 // Get a `PrintManager` instance.
2776 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2778 // Convert `mainWebView` to `printDocumentAdapter`.
2779 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2781 // Remove the lint error below that `printManager` might be `null`.
2782 assert printManager != null;
2784 // Print the document. The print attributes are `null`.
2785 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2788 case R.id.view_source:
2789 // Launch the View Source activity.
2790 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2791 startActivity(viewSourceIntent);
2794 case R.id.proxy_through_orbot:
2795 // Toggle the proxy through Orbot variable.
2796 proxyThroughOrbot = !proxyThroughOrbot;
2798 // Apply the proxy through Orbot settings.
2799 applyProxyThroughOrbot(true);
2803 // Setup the share string.
2804 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2806 // Create the share intent.
2807 Intent shareIntent = new Intent(Intent.ACTION_SEND);
2808 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2809 shareIntent.setType("text/plain");
2812 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2815 case R.id.find_on_page:
2816 // Hide the URL app bar.
2817 supportAppBar.setVisibility(View.GONE);
2819 // Show the Find on Page `RelativeLayout`.
2820 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2822 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2823 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2824 findOnPageEditText.postDelayed(() -> {
2825 // Set the focus on `findOnPageEditText`.
2826 findOnPageEditText.requestFocus();
2828 // Display the keyboard. `0` sets no input flags.
2829 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2833 case R.id.add_to_homescreen:
2834 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2835 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2836 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2838 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2842 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2843 // Reload the WebView.
2844 mainWebView.reload();
2845 } else { // The stop button was pushed.
2846 // Stop the loading of the WebView.
2847 mainWebView.stopLoading();
2851 case R.id.ad_consent:
2852 // Display the ad consent dialog.
2853 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2854 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2858 // Don't consume the event.
2859 return super.onOptionsItemSelected(menuItem);
2863 // removeAllCookies is deprecated, but it is required for API < 21.
2864 @SuppressWarnings("deprecation")
2866 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2867 int menuItemId = menuItem.getItemId();
2869 switch (menuItemId) {
2875 if (mainWebView.canGoBack()) {
2876 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2877 formattedUrlString = "";
2879 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2880 navigatingHistory = true;
2882 // Load the previous website in the history.
2883 mainWebView.goBack();
2888 if (mainWebView.canGoForward()) {
2889 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2890 formattedUrlString = "";
2892 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2893 navigatingHistory = true;
2895 // Load the next website in the history.
2896 mainWebView.goForward();
2901 // Get the `WebBackForwardList`.
2902 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2904 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2905 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2906 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2910 // Launch the requests activity.
2911 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2912 startActivity(requestsIntent);
2915 case R.id.downloads:
2916 // Launch the system Download Manager.
2917 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2919 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2920 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2922 startActivity(downloadManagerIntent);
2926 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2927 reapplyDomainSettingsOnRestart = true;
2928 currentDomainName = "";
2930 // Launch the domains activity.
2931 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2932 startActivity(domainsIntent);
2936 // Set the flag to reapply app settings on restart when returning from Settings.
2937 reapplyAppSettingsOnRestart = true;
2939 // Set the flag to reapply the domain settings on restart when returning from Settings.
2940 reapplyDomainSettingsOnRestart = true;
2941 currentDomainName = "";
2943 // Launch the settings activity.
2944 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2945 startActivity(settingsIntent);
2948 case R.id.import_export:
2949 // Launch the import/export activity.
2950 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2951 startActivity(importExportIntent);
2955 // Launch `GuideActivity`.
2956 Intent guideIntent = new Intent(this, GuideActivity.class);
2957 startActivity(guideIntent);
2961 // Launch `AboutActivity`.
2962 Intent aboutIntent = new Intent(this, AboutActivity.class);
2963 startActivity(aboutIntent);
2966 case R.id.clearAndExit:
2967 // Close the bookmarks cursor and database.
2968 bookmarksCursor.close();
2969 bookmarksDatabaseHelper.close();
2971 // Get a handle for `sharedPreferences`. `this` references the current context.
2972 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2974 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2977 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2978 // The command to remove cookies changed slightly in API 21.
2979 if (Build.VERSION.SDK_INT >= 21) {
2980 cookieManager.removeAllCookies(null);
2982 cookieManager.removeAllCookie();
2985 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2987 // We have to use two commands because `Runtime.exec()` does not like `*`.
2988 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2989 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2990 } catch (IOException e) {
2991 // Do nothing if an error is thrown.
2995 // Clear DOM storage.
2996 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2997 // Ask `WebStorage` to clear the DOM storage.
2998 WebStorage webStorage = WebStorage.getInstance();
2999 webStorage.deleteAllData();
3001 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
3003 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3004 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
3006 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
3007 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
3008 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
3009 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
3010 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
3011 } catch (IOException e) {
3012 // Do nothing if an error is thrown.
3016 // Clear form data if the API < 26.
3017 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
3018 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
3019 webViewDatabase.clearFormData();
3021 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
3023 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
3024 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
3025 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
3026 } catch (IOException e) {
3027 // Do nothing if an error is thrown.
3032 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
3033 // `true` includes disk files.
3034 mainWebView.clearCache(true);
3036 // Manually delete the cache directories.
3038 // Delete the main cache directory.
3039 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
3041 // Delete the secondary `Service Worker` cache directory.
3042 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
3043 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
3044 } catch (IOException e) {
3045 // Do nothing if an error is thrown.
3049 // Clear SSL certificate preferences.
3050 mainWebView.clearSslPreferences();
3052 // Clear the back/forward history.
3053 mainWebView.clearHistory();
3055 // Clear `formattedUrlString`.
3056 formattedUrlString = null;
3058 // Clear `customHeaders`.
3059 customHeaders.clear();
3061 // Detach all views from `mainWebViewRelativeLayout`.
3062 mainWebViewRelativeLayout.removeAllViews();
3064 // Destroy the internal state of `mainWebView`.
3065 mainWebView.destroy();
3067 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
3068 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
3069 if (clearEverything) {
3071 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
3072 } catch (IOException e) {
3073 // Do nothing if an error is thrown.
3077 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
3078 if (Build.VERSION.SDK_INT >= 21) {
3079 finishAndRemoveTask();
3084 // Remove the terminated program from RAM. The status code is `0`.
3089 // Close the navigation drawer.
3090 drawerLayout.closeDrawer(GravityCompat.START);
3095 public void onPostCreate(Bundle savedInstanceState) {
3096 super.onPostCreate(savedInstanceState);
3098 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
3099 drawerToggle.syncState();
3103 public void onConfigurationChanged(Configuration newConfig) {
3104 super.onConfigurationChanged(newConfig);
3106 // Reload the ad for the free flavor if we not in full screen mode.
3107 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
3108 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3109 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
3112 // `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:
3113 // https://code.google.com/p/android/issues/detail?id=20493#c8
3114 // ActivityCompat.invalidateOptionsMenu(this);
3118 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
3119 // Store the `HitTestResult`.
3120 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
3123 final String imageUrl;
3124 final String linkUrl;
3126 // Get a handle for the `ClipboardManager`.
3127 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
3129 // Remove the lint errors below that `clipboardManager` might be `null`.
3130 assert clipboardManager != null;
3132 switch (hitTestResult.getType()) {
3133 // `SRC_ANCHOR_TYPE` is a link.
3134 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
3135 // Get the target URL.
3136 linkUrl = hitTestResult.getExtra();
3138 // Set the target URL as the title of the `ContextMenu`.
3139 menu.setHeaderTitle(linkUrl);
3141 // Add a Load URL entry.
3142 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
3147 // Add a Copy URL entry.
3148 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
3149 // Save the link URL in a `ClipData`.
3150 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
3152 // Set the `ClipData` as the clipboard's primary clip.
3153 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
3157 // Add a Download URL entry.
3158 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
3159 // Check if the download should be processed by an external app.
3160 if (downloadWithExternalApp) { // Download with an external app.
3161 openUrlWithExternalApp(linkUrl);
3162 } else { // Download with Android's download manager.
3163 // Check to see if the storage permission has already been granted.
3164 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
3165 // Store the variables for future use by `onRequestPermissionsResult()`.
3166 downloadUrl = linkUrl;
3167 downloadContentDisposition = "none";
3168 downloadContentLength = -1;
3170 // Show a dialog if the user has previously denied the permission.
3171 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3172 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
3173 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
3175 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
3176 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3177 } else { // Show the permission request directly.
3178 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
3179 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3181 } else { // The storage permission has already been granted.
3182 // Get a handle for the download file alert dialog.
3183 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
3185 // Show the download file alert dialog.
3186 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3192 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3193 menu.add(R.string.cancel);
3196 case WebView.HitTestResult.EMAIL_TYPE:
3197 // Get the target URL.
3198 linkUrl = hitTestResult.getExtra();
3200 // Set the target URL as the title of the `ContextMenu`.
3201 menu.setHeaderTitle(linkUrl);
3203 // Add a `Write Email` entry.
3204 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
3205 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
3206 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
3208 // Parse the url and set it as the data for the `Intent`.
3209 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
3211 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
3212 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3215 startActivity(emailIntent);
3219 // Add a `Copy Email Address` entry.
3220 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
3221 // Save the email address in a `ClipData`.
3222 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
3224 // Set the `ClipData` as the clipboard's primary clip.
3225 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
3229 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3230 menu.add(R.string.cancel);
3233 // `IMAGE_TYPE` is an image.
3234 case WebView.HitTestResult.IMAGE_TYPE:
3235 // Get the image URL.
3236 imageUrl = hitTestResult.getExtra();
3238 // Set the image URL as the title of the `ContextMenu`.
3239 menu.setHeaderTitle(imageUrl);
3241 // Add a `View Image` entry.
3242 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3247 // Add a `Download Image` entry.
3248 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3249 // Check if the download should be processed by an external app.
3250 if (downloadWithExternalApp) { // Download with an external app.
3251 openUrlWithExternalApp(imageUrl);
3252 } else { // Download with Android's download manager.
3253 // Check to see if the storage permission has already been granted.
3254 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
3255 // Store the image URL for use by `onRequestPermissionResult()`.
3256 downloadImageUrl = imageUrl;
3258 // Show a dialog if the user has previously denied the permission.
3259 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3260 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3261 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3263 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3264 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3265 } else { // Show the permission request directly.
3266 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3267 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3269 } else { // The storage permission has already been granted.
3270 // Get a handle for the download image alert dialog.
3271 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3273 // Show the download image alert dialog.
3274 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3280 // Add a `Copy URL` entry.
3281 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3282 // Save the image URL in a `ClipData`.
3283 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3285 // Set the `ClipData` as the clipboard's primary clip.
3286 clipboardManager.setPrimaryClip(srcImageTypeClipData);
3290 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3291 menu.add(R.string.cancel);
3295 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
3296 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
3297 // Get the image URL.
3298 imageUrl = hitTestResult.getExtra();
3300 // Set the image URL as the title of the `ContextMenu`.
3301 menu.setHeaderTitle(imageUrl);
3303 // Add a `View Image` entry.
3304 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3309 // Add a `Download Image` entry.
3310 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3311 // Check if the download should be processed by an external app.
3312 if (downloadWithExternalApp) { // Download with an external app.
3313 openUrlWithExternalApp(imageUrl);
3314 } else { // Download with Android's download manager.
3315 // Check to see if the storage permission has already been granted.
3316 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
3317 // Store the image URL for use by `onRequestPermissionResult()`.
3318 downloadImageUrl = imageUrl;
3320 // Show a dialog if the user has previously denied the permission.
3321 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3322 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3323 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3325 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3326 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3327 } else { // Show the permission request directly.
3328 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3329 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3331 } else { // The storage permission has already been granted.
3332 // Get a handle for the download image alert dialog.
3333 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3335 // Show the download image alert dialog.
3336 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3342 // Add a `Copy URL` entry.
3343 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3344 // Save the image URL in a `ClipData`.
3345 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3347 // Set the `ClipData` as the clipboard's primary clip.
3348 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3352 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3353 menu.add(R.string.cancel);
3359 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3360 // Get the `EditTexts` from the `dialogFragment`.
3361 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3362 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3364 // Extract the strings from the `EditTexts`.
3365 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3366 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3368 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3369 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3370 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3371 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3373 // Display the new bookmark below the current items in the (0 indexed) list.
3374 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3376 // Create the bookmark.
3377 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3379 // Update `bookmarksCursor` with the current contents of this folder.
3380 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3382 // Update the `ListView`.
3383 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3385 // Scroll to the new bookmark.
3386 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3390 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3391 // Get handles for the views in `dialogFragment`.
3392 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3393 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3394 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3396 // Get new folder name string.
3397 String folderNameString = createFolderNameEditText.getText().toString();
3399 // Get the new folder icon `Bitmap`.
3400 Bitmap folderIconBitmap;
3401 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3402 // Get the default folder icon and convert it to a `Bitmap`.
3403 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3404 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3405 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3406 } else { // Use the `WebView` favorite icon.
3407 folderIconBitmap = favoriteIconBitmap;
3410 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3411 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3412 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3413 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3415 // Move all the bookmarks down one in the display order.
3416 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3417 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3418 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3421 // Create the folder, which will be placed at the top of the `ListView`.
3422 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3424 // Update `bookmarksCursor` with the current contents of this folder.
3425 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3427 // Update the `ListView`.
3428 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3430 // Scroll to the new folder.
3431 bookmarksListView.setSelection(0);
3435 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3436 // Get the shortcut name.
3437 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3438 String shortcutNameString = shortcutNameEditText.getText().toString();
3440 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3441 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3443 // Setup the shortcut intent.
3444 Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
3445 shortcutIntent.setData(Uri.parse(formattedUrlString));
3447 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3448 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3450 // Add the required fields to the shortcut info builder.
3451 shortcutInfoBuilder.setIcon(favoriteIcon);
3452 shortcutInfoBuilder.setIntent(shortcutIntent);
3453 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3455 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3456 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3460 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3461 switch (downloadType) {
3462 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3463 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3464 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3467 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3468 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3469 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3475 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
3476 switch (requestCode) {
3477 case DOWNLOAD_FILE_REQUEST_CODE:
3478 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3479 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3481 // On API 23, displaying the fragment must be delayed or the app will crash.
3482 if (Build.VERSION.SDK_INT == 23) {
3483 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3485 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3488 // Reset the download variables.
3490 downloadContentDisposition = "";
3491 downloadContentLength = 0;
3494 case DOWNLOAD_IMAGE_REQUEST_CODE:
3495 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3496 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3498 // On API 23, displaying the fragment must be delayed or the app will crash.
3499 if (Build.VERSION.SDK_INT == 23) {
3500 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3502 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3505 // Reset the image URL variable.
3506 downloadImageUrl = "";
3512 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3513 // Download the image if it has an HTTP or HTTPS URI.
3514 if (imageUrl.startsWith("http")) {
3515 // Get a handle for the system `DOWNLOAD_SERVICE`.
3516 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3518 // Parse `imageUrl`.
3519 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3521 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3522 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3523 if (firstPartyCookiesEnabled) {
3524 // Get the cookies for `imageUrl`.
3525 String cookies = cookieManager.getCookie(imageUrl);
3527 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3528 downloadRequest.addRequestHeader("Cookie", cookies);
3531 // Get the file name from the dialog fragment.
3532 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3533 String imageName = downloadImageNameEditText.getText().toString();
3535 // Specify the download location.
3536 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3537 // Download to the public download directory.
3538 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3539 } else { // External write permission denied.
3540 // Download to the app's external download directory.
3541 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3544 // Allow `MediaScanner` to index the download if it is a media file.
3545 downloadRequest.allowScanningByMediaScanner();
3547 // Add the URL as the description for the download.
3548 downloadRequest.setDescription(imageUrl);
3550 // Show the download notification after the download is completed.
3551 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3553 // Remove the lint warning below that `downloadManager` might be `null`.
3554 assert downloadManager != null;
3556 // Initiate the download.
3557 downloadManager.enqueue(downloadRequest);
3558 } else { // The image is not an HTTP or HTTPS URI.
3559 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3564 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3565 // Download the file if it has an HTTP or HTTPS URI.
3566 if (downloadUrl.startsWith("http")) {
3567 // Get a handle for the system `DOWNLOAD_SERVICE`.
3568 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3570 // Parse `downloadUrl`.
3571 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3573 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3574 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3575 if (firstPartyCookiesEnabled) {
3576 // Get the cookies for `downloadUrl`.
3577 String cookies = cookieManager.getCookie(downloadUrl);
3579 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3580 downloadRequest.addRequestHeader("Cookie", cookies);
3583 // Get the file name from the dialog fragment.
3584 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3585 String fileName = downloadFileNameEditText.getText().toString();
3587 // Specify the download location.
3588 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3589 // Download to the public download directory.
3590 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3591 } else { // External write permission denied.
3592 // Download to the app's external download directory.
3593 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3596 // Allow `MediaScanner` to index the download if it is a media file.
3597 downloadRequest.allowScanningByMediaScanner();
3599 // Add the URL as the description for the download.
3600 downloadRequest.setDescription(downloadUrl);
3602 // Show the download notification after the download is completed.
3603 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3605 // Remove the lint warning below that `downloadManager` might be `null`.
3606 assert downloadManager != null;
3608 // Initiate the download.
3609 downloadManager.enqueue(downloadRequest);
3610 } else { // The download is not an HTTP or HTTPS URI.
3611 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3616 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3617 // Get handles for the views from `dialogFragment`.
3618 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3619 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3620 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3622 // Store the bookmark strings.
3623 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3624 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3626 // Update the bookmark.
3627 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3628 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3629 } else { // Update the bookmark using the `WebView` favorite icon.
3630 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3631 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3632 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3633 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3635 // Update the bookmark and the favorite icon.
3636 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3639 // Update `bookmarksCursor` with the current contents of this folder.
3640 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3642 // Update the `ListView`.
3643 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3647 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3648 // Get handles for the views from `dialogFragment`.
3649 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3650 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3651 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3652 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3654 // Get the new folder name.
3655 String newFolderNameString = editFolderNameEditText.getText().toString();
3657 // Check if the favorite icon has changed.
3658 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3659 // Update the name in the database.
3660 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3661 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3662 // Get the new folder icon `Bitmap`.
3663 Bitmap folderIconBitmap;
3664 if (defaultFolderIconRadioButton.isChecked()) {
3665 // Get the default folder icon and convert it to a `Bitmap`.
3666 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3667 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3668 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3669 } else { // Use the `WebView` favorite icon.
3670 folderIconBitmap = favoriteIconBitmap;
3673 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3674 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3675 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3676 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3678 // Update the folder icon in the database.
3679 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3680 } else { // The folder icon and the name have changed.
3681 // Get the new folder icon `Bitmap`.
3682 Bitmap folderIconBitmap;
3683 if (defaultFolderIconRadioButton.isChecked()) {
3684 // Get the default folder icon and convert it to a `Bitmap`.
3685 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3686 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3687 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3688 } else { // Use the `WebView` favorite icon.
3689 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3692 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3693 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3694 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3695 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3697 // Update the folder name and icon in the database.
3698 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3701 // Update `bookmarksCursor` with the current contents of this folder.
3702 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3704 // Update the `ListView`.
3705 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3709 public void onHttpAuthenticationCancel() {
3710 // Cancel the `HttpAuthHandler`.
3711 httpAuthHandler.cancel();
3715 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3716 // Get handles for the `EditTexts`.
3717 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3718 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3720 // Proceed with the HTTP authentication.
3721 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3724 public void viewSslCertificate(View view) {
3725 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3726 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3727 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3731 public void onSslErrorCancel() {
3732 sslErrorHandler.cancel();
3736 public void onSslErrorProceed() {
3737 sslErrorHandler.proceed();
3741 public void onSslMismatchBack() {
3742 if (mainWebView.canGoBack()) { // There is a back page in the history.
3743 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3744 formattedUrlString = "";
3746 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3747 navigatingHistory = true;
3750 mainWebView.goBack();
3751 } else { // There are no pages to go back to.
3752 // Load a blank page
3758 public void onSslMismatchProceed() {
3759 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3760 ignorePinnedSslCertificate = true;
3764 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3765 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3766 formattedUrlString = "";
3768 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3769 navigatingHistory = true;
3771 // Load the history entry.
3772 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3776 public void onClearHistory() {
3777 // Clear the history.
3778 mainWebView.clearHistory();
3781 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3783 public void onBackPressed() {
3784 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3785 // Close the navigation drawer.
3786 drawerLayout.closeDrawer(GravityCompat.START);
3787 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3788 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3789 // close the bookmarks drawer.
3790 drawerLayout.closeDrawer(GravityCompat.END);
3791 } else { // A subfolder is displayed.
3792 // Place the former parent folder in `currentFolder`.
3793 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3795 // Load the new folder.
3796 loadBookmarksFolder();
3799 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3800 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3801 formattedUrlString = "";
3803 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3804 navigatingHistory = true;
3807 mainWebView.goBack();
3808 } else { // There isn't anything to do in Privacy Browser.
3809 // Pass `onBackPressed()` to the system.
3810 super.onBackPressed();
3814 // 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.
3816 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3817 // File uploads only work on API >= 21.
3818 if (Build.VERSION.SDK_INT >= 21) {
3819 // Pass the file to the WebView.
3820 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3824 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3825 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3826 String unformattedUrlString = urlTextBox.getText().toString().trim();
3828 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3829 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3830 // Add `https://` at the beginning if it is missing. Otherwise the app will segfault.
3831 if (!unformattedUrlString.startsWith("http")) {
3832 unformattedUrlString = "https://" + unformattedUrlString;
3835 // Initialize `unformattedUrl`.
3836 URL unformattedUrl = null;
3838 // 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.
3840 unformattedUrl = new URL(unformattedUrlString);
3841 } catch (MalformedURLException e) {
3842 e.printStackTrace();
3845 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3846 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3847 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3848 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3849 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3850 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3853 Uri.Builder formattedUri = new Uri.Builder();
3854 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3856 // Decode `formattedUri` as a `String` in `UTF-8`.
3857 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3858 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3859 // Load a blank string.
3860 formattedUrlString = "";
3861 } else { // Search for the contents of the URL box.
3862 // Sanitize the search input and convert it to a search.
3863 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3865 // Add the base search URL.
3866 formattedUrlString = searchURL + encodedUrlString;
3869 // 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.
3870 urlTextBox.clearFocus();
3873 loadUrl(formattedUrlString);
3876 private void loadUrl(String url) {// Apply any custom domain settings.
3877 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3878 formattedUrlString = url;
3880 // Apply the domain settings.
3881 applyDomainSettings(url, true, false);
3883 // If loading a website, set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3884 urlIsLoading = !url.equals("");
3887 mainWebView.loadUrl(url, customHeaders);
3890 public void findPreviousOnPage(View view) {
3891 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3892 mainWebView.findNext(false);
3895 public void findNextOnPage(View view) {
3896 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3897 mainWebView.findNext(true);
3900 public void closeFindOnPage(View view) {
3901 // Delete the contents of `find_on_page_edittext`.
3902 findOnPageEditText.setText(null);
3904 // Clear the highlighted phrases.
3905 mainWebView.clearMatches();
3907 // Hide the Find on Page `RelativeLayout`.
3908 findOnPageLinearLayout.setVisibility(View.GONE);
3910 // Show the URL app bar.
3911 supportAppBar.setVisibility(View.VISIBLE);
3913 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3914 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3917 private void applyAppSettings() {
3918 // Get a handle for the shared preferences.
3919 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3921 // Store the values from the shared preferences in variables.
3922 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3923 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3924 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3925 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3926 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3927 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3928 downloadWithExternalApp = sharedPreferences.getBoolean("download_with_external_app", false);
3930 // Apply the proxy through Orbot settings.
3931 applyProxyThroughOrbot(false);
3933 // Set Do Not Track status.
3934 if (doNotTrackEnabled) {
3935 customHeaders.put("DNT", "1");
3937 customHeaders.remove("DNT");
3940 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3941 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3942 if (hideSystemBarsOnFullscreen) { // Hide everything.
3943 // Remove the translucent navigation setting if it is currently flagged.
3944 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3946 // Remove the translucent status bar overlay.
3947 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3949 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3950 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3952 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3953 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3954 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3956 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3957 } else { // Hide everything except the status and navigation bars.
3958 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3959 rootCoordinatorLayout.setSystemUiVisibility(0);
3961 // Add the translucent status flag if it is unset.
3962 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3964 if (translucentNavigationBarOnFullscreen) {
3965 // Set the navigation bar to be translucent.
3966 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3968 // Set the navigation bar to be black.
3969 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3972 } else { // Privacy Browser is not in full screen browsing mode.
3973 // 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.
3974 inFullScreenBrowsingMode = false;
3976 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3977 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3981 // Show the `BannerAd` in the free flavor.
3982 if (BuildConfig.FLAVOR.contentEquals("free")) {
3983 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3984 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3987 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3988 rootCoordinatorLayout.setSystemUiVisibility(0);
3990 // Remove the translucent navigation bar flag if it is set.
3991 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3993 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3994 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3996 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3997 rootCoordinatorLayout.setFitsSystemWindows(true);
4001 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
4002 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
4003 @SuppressWarnings("deprecation")
4004 private boolean applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
4005 // Get the current user agent.
4006 String initialUserAgent = mainWebView.getSettings().getUserAgentString();
4008 // Initialize a variable to track if the user agent changes.
4009 boolean userAgentChanged = false;
4011 // Parse the URL into a URI.
4012 Uri uri = Uri.parse(url);
4014 // Extract the domain from `uri`.
4015 String hostName = uri.getHost();
4017 // Initialize `loadingNewDomainName`.
4018 boolean loadingNewDomainName;
4020 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
4021 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
4022 //noinspection SimplifiableIfStatement
4023 if ((hostName == null) || (currentDomainName == null)) {
4024 loadingNewDomainName = true;
4025 } else { // Determine if `hostName` equals `currentDomainName`.
4026 loadingNewDomainName = !hostName.equals(currentDomainName);
4029 // Strings don't like to be null.
4030 if (hostName == null) {
4034 // 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.
4035 if (loadingNewDomainName) {
4036 // Set the new `hostname` as the `currentDomainName`.
4037 currentDomainName = hostName;
4039 // Reset `ignorePinnedSslCertificate`.
4040 ignorePinnedSslCertificate = false;
4042 // Reset the favorite icon if specified.
4043 if (resetFavoriteIcon) {
4044 favoriteIconBitmap = favoriteIconDefaultBitmap;
4045 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
4048 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
4049 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
4051 // Get a full cursor from `domainsDatabaseHelper`.
4052 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
4054 // Initialize `domainSettingsSet`.
4055 Set<String> domainSettingsSet = new HashSet<>();
4057 // Get the domain name column index.
4058 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
4060 // Populate `domainSettingsSet`.
4061 for (int i = 0; i < domainNameCursor.getCount(); i++) {
4062 // Move `domainsCursor` to the current row.
4063 domainNameCursor.moveToPosition(i);
4065 // Store the domain name in `domainSettingsSet`.
4066 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
4069 // Close `domainNameCursor.
4070 domainNameCursor.close();
4072 // Initialize variables to track if domain settings will be applied and, if so, under which name.
4073 domainSettingsApplied = false;
4074 String domainNameInDatabase = null;
4076 // Check the hostname.
4077 if (domainSettingsSet.contains(hostName)) {
4078 domainSettingsApplied = true;
4079 domainNameInDatabase = hostName;
4082 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
4083 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
4084 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
4085 // Apply the domain settings.
4086 domainSettingsApplied = true;
4088 // Store the applied domain names as it appears in the database.
4089 domainNameInDatabase = "*." + hostName;
4092 // Strip out the lowest subdomain of of the host name.
4093 hostName = hostName.substring(hostName.indexOf(".") + 1);
4097 // Get a handle for the shared preference.
4098 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4100 // Store the general preference information.
4101 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
4102 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
4103 defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value));
4104 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
4105 nightMode = sharedPreferences.getBoolean("night_mode", false);
4106 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
4108 if (domainSettingsApplied) { // The url has custom domain settings.
4109 // Get a cursor for the current host and move it to the first position.
4110 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
4111 currentHostDomainSettingsCursor.moveToFirst();
4113 // Get the settings from the cursor.
4114 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
4115 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
4116 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
4117 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
4118 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
4119 // Form data can be removed once the minimum API >= 26.
4120 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
4121 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
4122 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
4123 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
4124 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
4125 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
4126 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
4127 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
4128 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
4129 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
4130 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
4131 int displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
4132 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
4133 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
4134 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
4135 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
4136 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
4137 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
4138 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
4140 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
4141 switch (nightModeInt) {
4142 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
4146 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
4151 // Store the domain JavaScript status. This is used by the options menu night mode toggle.
4152 domainSettingsJavaScriptEnabled = javaScriptEnabled;
4154 // Enable JavaScript if night mode is enabled.
4156 javaScriptEnabled = true;
4159 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
4160 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
4161 pinnedDomainSslStartDate = null;
4163 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
4166 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
4167 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
4168 pinnedDomainSslEndDate = null;
4170 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
4173 // Close `currentHostDomainSettingsCursor`.
4174 currentHostDomainSettingsCursor.close();
4176 // Apply the domain settings.
4177 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4178 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4179 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4181 // Apply the form data setting if the API < 26.
4182 if (Build.VERSION.SDK_INT < 26) {
4183 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4186 // Apply the font size.
4187 if (fontSize == 0) { // Apply the default font size.
4188 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4189 } else { // Apply the specified font size.
4190 mainWebView.getSettings().setTextZoom(fontSize);
4193 // Set third-party cookies status if API >= 21.
4194 if (Build.VERSION.SDK_INT >= 21) {
4195 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4198 // 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.
4199 // <https://redmine.stoutner.com/issues/160>
4200 if (!urlIsLoading) {
4201 // Set the user agent.
4202 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4203 // Get the array position of the default user agent name.
4204 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4206 // Set the user agent according to the system default.
4207 switch (defaultUserAgentArrayPosition) {
4208 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4209 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4210 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4213 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4214 // Set the user agent to `""`, which uses the default value.
4215 mainWebView.getSettings().setUserAgentString("");
4218 case SETTINGS_CUSTOM_USER_AGENT:
4219 // Set the custom user agent.
4220 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4224 // Get the user agent string from the user agent data array
4225 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4227 } else { // Set the user agent according to the stored name.
4228 // Get the array position of the user agent name.
4229 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4231 switch (userAgentArrayPosition) {
4232 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4233 mainWebView.getSettings().setUserAgentString(userAgentName);
4236 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4237 // Set the user agent to `""`, which uses the default value.
4238 mainWebView.getSettings().setUserAgentString("");
4242 // Get the user agent string from the user agent data array.
4243 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4247 // Store the applied user agent string, which is used in the View Source activity.
4248 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4250 // Update the user agent change tracker.
4251 userAgentChanged = !appliedUserAgentString.equals(initialUserAgent);
4254 // Set swipe to refresh.
4255 switch (swipeToRefreshInt) {
4256 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
4257 // Set swipe to refresh according to the default.
4258 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4261 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
4262 // Enable swipe to refresh.
4263 swipeRefreshLayout.setEnabled(true);
4266 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
4267 // Disable swipe to refresh.
4268 swipeRefreshLayout.setEnabled(false);
4271 // Set the loading of webpage images.
4272 switch (displayWebpageImagesInt) {
4273 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4274 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4277 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4278 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4281 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4282 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4286 // 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.
4288 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4290 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4292 } else { // The new URL does not have custom domain settings. Load the defaults.
4293 // Store the values from `sharedPreferences` in variables.
4294 javaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
4295 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies", false);
4296 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
4297 domStorageEnabled = sharedPreferences.getBoolean("dom_storage", false);
4298 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4299 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
4300 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
4301 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboys_annoyance_list", true);
4302 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboys_social_blocking_list", true);
4303 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
4304 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
4306 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4308 javaScriptEnabled = true;
4311 // Apply the default settings.
4312 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4313 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4314 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4315 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4316 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4318 // Apply the form data setting if the API < 26.
4319 if (Build.VERSION.SDK_INT < 26) {
4320 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4323 // Reset the pinned SSL certificate information.
4324 domainSettingsDatabaseId = -1;
4325 pinnedDomainSslCertificate = false;
4326 pinnedDomainSslIssuedToCNameString = "";
4327 pinnedDomainSslIssuedToONameString = "";
4328 pinnedDomainSslIssuedToUNameString = "";
4329 pinnedDomainSslIssuedByCNameString = "";
4330 pinnedDomainSslIssuedByONameString = "";
4331 pinnedDomainSslIssuedByUNameString = "";
4332 pinnedDomainSslStartDate = null;
4333 pinnedDomainSslEndDate = null;
4335 // Set third-party cookies status if API >= 21.
4336 if (Build.VERSION.SDK_INT >= 21) {
4337 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4340 // 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.
4341 // <https://redmine.stoutner.com/issues/160>
4342 if (!urlIsLoading) {
4343 // Get the array position of the user agent name.
4344 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4346 // Set the user agent.
4347 switch (userAgentArrayPosition) {
4348 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4349 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4350 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4353 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4354 // Set the user agent to `""`, which uses the default value.
4355 mainWebView.getSettings().setUserAgentString("");
4358 case SETTINGS_CUSTOM_USER_AGENT:
4359 // Set the custom user agent.
4360 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4364 // Get the user agent string from the user agent data array
4365 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4368 // Store the applied user agent string, which is used in the View Source activity.
4369 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4371 // Update the user agent change tracker.
4372 userAgentChanged = !appliedUserAgentString.equals(initialUserAgent);
4375 // Set the loading of webpage images.
4376 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4378 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4379 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4382 // Close the domains database helper.
4383 domainsDatabaseHelper.close();
4385 // Update the privacy icons, but only if `mainMenu` has already been populated.
4386 if (mainMenu != null) {
4387 updatePrivacyIcons(true);
4391 // Reload the website if returning from the Domains activity.
4392 if (reloadWebsite) {
4393 mainWebView.reload();
4396 // Return the user agent changed status.
4397 return userAgentChanged;
4400 private void applyProxyThroughOrbot(boolean reloadWebsite) {
4401 // Get a handle for the shared preferences.
4402 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4404 // Get the search preferences.
4405 String homepageString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
4406 String torHomepageString = sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value));
4407 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
4408 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
4409 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
4410 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
4412 // Set the homepage, search, and proxy options.
4413 if (proxyThroughOrbot) { // Set the Tor options.
4414 // Set `torHomepageString` as `homepage`.
4415 homepage = torHomepageString;
4417 // If formattedUrlString is null assign the homepage to it.
4418 if (formattedUrlString == null) {
4419 formattedUrlString = homepage;
4422 // Set the search URL.
4423 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
4424 searchURL = torSearchCustomUrlString;
4425 } else { // Use the string from the pre-built list.
4426 searchURL = torSearchString;
4429 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
4430 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
4432 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
4434 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
4436 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
4439 // Check to see if Orbot is ready.
4440 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4441 // Set `waitingForOrbot`.
4442 waitingForOrbot = true;
4444 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
4445 mainWebView.getSettings().setUseWideViewPort(false);
4447 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
4448 mainWebView.loadData(waitingForOrbotHtmlString, "text/html", null);
4449 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
4450 // Reload the website.
4451 mainWebView.reload();
4453 } else { // Set the non-Tor options.
4454 // Set `homepageString` as `homepage`.
4455 homepage = homepageString;
4457 // If formattedUrlString is null assign the homepage to it.
4458 if (formattedUrlString == null) {
4459 formattedUrlString = homepage;
4462 // Set the search URL.
4463 if (searchString.equals("Custom URL")) { // Get the custom URL string.
4464 searchURL = searchCustomUrlString;
4465 } else { // Use the string from the pre-built list.
4466 searchURL = searchString;
4469 // Reset the proxy to default. The host is `""` and the port is `"0"`.
4470 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
4472 // Set the default `appBar` background. `this` refers to the context.
4474 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
4476 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
4479 // Reset `waitingForOrbot.
4480 waitingForOrbot = false;
4482 // Reload the website if requested.
4483 if (reloadWebsite) {
4484 mainWebView.reload();
4489 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4490 // Get handles for the menu items.
4491 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4492 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4493 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4494 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4496 // Update the privacy icon.
4497 if (javaScriptEnabled) { // JavaScript is enabled.
4498 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4499 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4500 privacyMenuItem.setIcon(R.drawable.warning);
4501 } else { // All the dangerous features are disabled.
4502 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4505 // Update the first-party cookies icon.
4506 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4507 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4508 } else { // First-party cookies are disabled.
4510 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4512 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4516 // Update the DOM storage icon.
4517 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4518 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4519 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4521 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4523 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4525 } else { // JavaScript is disabled, so DOM storage is ghosted.
4527 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4529 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4533 // Update the refresh icon.
4535 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4537 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4540 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4541 if (runInvalidateOptionsMenu) {
4542 invalidateOptionsMenu();
4546 private void openUrlWithExternalApp(String url) {
4547 // Create a download intent. Not specifying the action type will display the maximum number of options.
4548 Intent downloadIntent = new Intent();
4550 // Set the URI and the mime type. `"*/*"` will display the maximum number of options.
4551 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
4553 // Flag the intent to open in a new task.
4554 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4556 // Show the chooser.
4557 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4560 private void highlightUrlText() {
4561 // Get the URL string.
4562 String urlString = urlTextBox.getText().toString();
4564 // Get the index of the `/` immediately after the domain name.
4565 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4567 // Create a base URL string.
4570 // Get the base URL.
4571 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4572 // Get the base URL.
4573 baseUrl = urlString.substring(0, endOfDomainName);
4574 } else { // There are no characters after the base URL.
4575 // Set the base URL to be the entire URL string.
4576 baseUrl = urlString;
4579 // Get the index of the last `.` in the domain.
4580 int lastDotIndex = baseUrl.lastIndexOf(".");
4582 // Get the index of the penultimate `.` in the domain.
4583 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4585 // Markup the beginning of the URL.
4586 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4587 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4589 // De-emphasize subdomains.
4590 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4591 urlTextBox.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4593 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4594 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4595 // De-emphasize the protocol and the additional subdomains.
4596 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4597 } else { // There is only one subdomain in the domain name.
4598 // De-emphasize only the protocol.
4599 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4603 // De-emphasize the text after the domain name.
4604 if (endOfDomainName > 0) {
4605 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4609 private void loadBookmarksFolder() {
4610 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4611 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4613 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4614 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4616 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4617 // Inflate the individual item layout. `false` does not attach it to the root.
4618 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4622 public void bindView(View view, Context context, Cursor cursor) {
4623 // Get handles for the views.
4624 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4625 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4627 // Get the favorite icon byte array from the cursor.
4628 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4630 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4631 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4633 // Display the bitmap in `bookmarkFavoriteIcon`.
4634 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4636 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4637 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4638 bookmarkNameTextView.setText(bookmarkNameString);
4640 // Make the font bold for folders.
4641 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4642 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4643 } else { // Reset the font to default for normal bookmarks.
4644 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4649 // Populate the `ListView` with the adapter.
4650 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4652 // Set the bookmarks drawer title.
4653 if (currentBookmarksFolder.isEmpty()) {
4654 bookmarksTitleTextView.setText(R.string.bookmarks);
4656 bookmarksTitleTextView.setText(currentBookmarksFolder);