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.swiperefreshlayout);
820 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
822 // Set the swipe to refresh color according to the theme.
824 swipeRefreshLayout.setColorSchemeResources(R.color.blue_600);
825 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
827 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
830 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
831 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
832 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
834 // Listen for touches on the navigation menu.
835 final NavigationView navigationView = findViewById(R.id.navigationview);
836 navigationView.setNavigationItemSelectedListener(this);
838 // 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.
839 final Menu navigationMenu = navigationView.getMenu();
840 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
841 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
842 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
843 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
845 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
846 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
847 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
849 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
850 currentBookmarksFolder = "";
852 // Load the home folder, which is `""` in the database.
853 loadBookmarksFolder();
855 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
856 // Convert the id from long to int to match the format of the bookmarks database.
857 int databaseID = (int) id;
859 // Get the bookmark cursor for this ID and move it to the first row.
860 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
861 bookmarkCursor.moveToFirst();
863 // Act upon the bookmark according to the type.
864 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
865 // Store the new folder name in `currentBookmarksFolder`.
866 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
868 // Load the new folder.
869 loadBookmarksFolder();
870 } else { // The selected bookmark is not a folder.
871 // Load the bookmark URL.
872 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
874 // Close the bookmarks drawer.
875 drawerLayout.closeDrawer(GravityCompat.END);
878 // Close the `Cursor`.
879 bookmarkCursor.close();
882 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
883 // Convert the database ID from `long` to `int`.
884 int databaseId = (int) id;
886 // Find out if the selected bookmark is a folder.
887 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
890 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
891 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
893 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
894 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
895 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
897 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
898 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
899 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
902 // Consume the event.
906 // The drawer listener is used to update the navigation menu.
907 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
909 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
913 public void onDrawerOpened(@NonNull View drawerView) {
917 public void onDrawerClosed(@NonNull View drawerView) {
921 public void onDrawerStateChanged(int newState) {
922 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
923 // Update the back, forward, history, and requests menu items.
924 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
925 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
926 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
927 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
929 // Hide the keyboard (if displayed).
930 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
932 // Clear the focus from from the URL text box and the WebView. This removes any text selection markers and context menus, which otherwise draw above the open drawers.
933 urlTextBox.clearFocus();
934 mainWebView.clearFocus();
939 // drawerToggle creates the hamburger icon at the start of the AppBar.
940 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
942 // Get a handle for the progress bar.
943 final ProgressBar progressBar = findViewById(R.id.progress_bar);
945 mainWebView.setWebChromeClient(new WebChromeClient() {
946 // Update the progress bar when a page is loading.
948 public void onProgressChanged(WebView view, int progress) {
949 // Inject the night mode CSS if night mode is enabled.
951 // `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
952 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
953 // `border: none` removes all borders, which can also be used to underline text.
954 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
955 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
956 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
957 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
958 // Initialize a handler to display `mainWebView`.
959 Handler displayWebViewHandler = new Handler();
961 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
962 Runnable displayWebViewRunnable = () -> {
963 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
964 if (progressBar.getVisibility() == View.GONE) {
965 mainWebView.setVisibility(View.VISIBLE);
969 // Displaying of `mainWebView` after 500 milliseconds.
970 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
974 // Update the progress bar.
975 progressBar.setProgress(progress);
977 // Set the visibility of the progress bar.
978 if (progress < 100) {
979 // Show the progress bar.
980 progressBar.setVisibility(View.VISIBLE);
982 // Hide the progress bar.
983 progressBar.setVisibility(View.GONE);
985 // Display `mainWebView` if night mode is disabled.
986 // 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
987 // currently enabled.
989 mainWebView.setVisibility(View.VISIBLE);
992 //Stop the swipe to refresh indicator if it is running
993 swipeRefreshLayout.setRefreshing(false);
997 // Set the favorite icon when it changes.
999 public void onReceivedIcon(WebView view, Bitmap icon) {
1000 // Only update the favorite icon if the website has finished loading.
1001 if (progressBar.getVisibility() == View.GONE) {
1002 // Save a copy of the favorite icon.
1003 favoriteIconBitmap = icon;
1005 // Place the favorite icon in the appBar.
1006 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1010 // Save a copy of the title when it changes.
1012 public void onReceivedTitle(WebView view, String title) {
1013 // Save a copy of the title.
1014 webViewTitle = title;
1017 // Enter full screen video.
1019 public void onShowCustomView(View view, CustomViewCallback callback) {
1020 // Set the full screen video flag.
1021 displayingFullScreenVideo = true;
1023 // Pause the ad if this is the free flavor.
1024 if (BuildConfig.FLAVOR.contentEquals("free")) {
1025 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1026 AdHelper.pauseAd(findViewById(R.id.adview));
1029 // Remove the translucent overlays.
1030 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1032 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1033 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1035 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1036 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1037 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1039 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1041 // Set `rootCoordinatorLayout` to fill the entire screen.
1042 rootCoordinatorLayout.setFitsSystemWindows(false);
1044 // Disable the sliding drawers.
1045 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1047 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1048 fullScreenVideoFrameLayout.addView(view);
1049 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1052 // Exit full screen video.
1054 public void onHideCustomView() {
1055 // Unset the full screen video flag.
1056 displayingFullScreenVideo = false;
1058 // Hide `fullScreenVideoFrameLayout`.
1059 fullScreenVideoFrameLayout.removeAllViews();
1060 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1062 // Enable the sliding drawers.
1063 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1065 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1066 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1067 if (hideSystemBarsOnFullscreen) { // Hide everything.
1068 // Remove the translucent navigation setting if it is currently flagged.
1069 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1071 // Remove the translucent status bar overlay.
1072 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1074 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1075 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1077 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1078 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1079 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1081 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1082 } else { // Hide everything except the status and navigation bars.
1083 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1084 rootCoordinatorLayout.setSystemUiVisibility(0);
1086 // Add the translucent status flag if it is unset.
1087 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1089 if (translucentNavigationBarOnFullscreen) {
1090 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1091 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1093 // Set the navigation bar to be black.
1094 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1097 } else { // Switch to normal viewing mode.
1098 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1099 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1103 // Show the `BannerAd` in the free flavor.
1104 if (BuildConfig.FLAVOR.contentEquals("free")) {
1105 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1106 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
1109 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1110 rootCoordinatorLayout.setSystemUiVisibility(0);
1112 // Remove the translucent navigation bar flag if it is set.
1113 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1115 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1116 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1118 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1119 rootCoordinatorLayout.setFitsSystemWindows(true);
1122 // Show the ad if this is the free flavor.
1123 if (BuildConfig.FLAVOR.contentEquals("free")) {
1124 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1125 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
1131 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1132 // Show the file chooser if the device is running API >= 21.
1133 if (Build.VERSION.SDK_INT >= 21) {
1134 // Store the file path callback.
1135 fileChooserCallback = filePathCallback;
1137 // Create an intent to open a chooser based ont the file chooser parameters.
1138 Intent fileChooserIntent = fileChooserParams.createIntent();
1140 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1141 startActivityForResult(fileChooserIntent, 0);
1147 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1148 registerForContextMenu(mainWebView);
1150 // Allow the downloading of files.
1151 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1152 // Check if the download should be processed by an external app.
1153 if (downloadWithExternalApp) { // Download with an external app.
1154 openUrlWithExternalApp(url);
1155 } else { // Download with Android's download manager.
1156 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1157 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
1158 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1160 // Store the variables for future use by `onRequestPermissionsResult()`.
1162 downloadContentDisposition = contentDisposition;
1163 downloadContentLength = contentLength;
1165 // Show a dialog if the user has previously denied the permission.
1166 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1167 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1168 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1170 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1171 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1172 } else { // Show the permission request directly.
1173 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1174 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1176 } else { // The storage permission has already been granted.
1177 // Get a handle for the download file alert dialog.
1178 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1180 // Show the download file alert dialog.
1181 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1186 // Allow pinch to zoom.
1187 mainWebView.getSettings().setBuiltInZoomControls(true);
1189 // Hide zoom controls.
1190 mainWebView.getSettings().setDisplayZoomControls(false);
1192 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1193 mainWebView.getSettings().setUseWideViewPort(true);
1195 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1196 mainWebView.getSettings().setLoadWithOverviewMode(true);
1198 // Explicitly disable geolocation.
1199 mainWebView.getSettings().setGeolocationEnabled(false);
1201 // Initialize cookieManager.
1202 cookieManager = CookieManager.getInstance();
1204 // 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).
1205 customHeaders.put("X-Requested-With", "");
1207 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1208 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1210 // Get the intent that started the app.
1211 final Intent launchingIntent = getIntent();
1213 // Extract the launching intent data as `launchingIntentUriData`.
1214 final Uri launchingIntentUriData = launchingIntent.getData();
1216 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1217 if (launchingIntentUriData != null) {
1218 formattedUrlString = launchingIntentUriData.toString();
1221 // Get a handle for the `Runtime`.
1222 privacyBrowserRuntime = Runtime.getRuntime();
1224 // Store the application's private data directory.
1225 privateDataDirectoryString = getApplicationInfo().dataDir;
1226 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1228 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1229 inFullScreenBrowsingMode = false;
1231 // Initialize the privacy settings variables.
1232 javaScriptEnabled = false;
1233 firstPartyCookiesEnabled = false;
1234 thirdPartyCookiesEnabled = false;
1235 domStorageEnabled = false;
1236 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1239 // Store the default user agent.
1240 webViewDefaultUserAgent = mainWebView.getSettings().getUserAgentString();
1242 // Initialize the WebView title.
1243 webViewTitle = getString(R.string.no_title);
1245 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1246 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1247 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1248 assert favoriteIconBitmapDrawable != null;
1249 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1251 // If the favorite icon is null, load the default.
1252 if (favoriteIconBitmap == null) {
1253 favoriteIconBitmap = favoriteIconDefaultBitmap;
1256 // Initialize the user agent array adapter and string array.
1257 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
1258 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1260 // Apply the app settings from the shared preferences.
1263 // Instantiate the block list helper.
1264 BlockListHelper blockListHelper = new BlockListHelper();
1266 // Initialize the list of resource requests.
1267 resourceRequests = new ArrayList<>();
1269 // Parse the block lists.
1270 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1271 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1272 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1273 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1274 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1276 // Store the list versions.
1277 easyListVersion = easyList.get(0).get(0)[0];
1278 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1279 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1280 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1281 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1283 // Get a handle for the activity. This is used to update the requests counter while the navigation menu is open.
1284 Activity activity = this;
1286 mainWebView.setWebViewClient(new WebViewClient() {
1287 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1288 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1289 @SuppressWarnings("deprecation")
1291 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1292 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1293 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1294 formattedUrlString = "";
1296 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1297 boolean userAgentChanged = applyDomainSettings(url, true, false);
1299 // Check if the user agent has changed.
1300 if (userAgentChanged) {
1301 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
1302 mainWebView.loadUrl(url, customHeaders);
1304 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
1307 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1310 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1311 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1312 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1314 // Parse the url and set it as the data for the intent.
1315 emailIntent.setData(Uri.parse(url));
1317 // Open the email program in a new task instead of as part of Privacy Browser.
1318 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1321 startActivity(emailIntent);
1323 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1325 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1326 // Open the dialer and load the phone number, but wait for the user to place the call.
1327 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1329 // Add the phone number to the intent.
1330 dialIntent.setData(Uri.parse(url));
1332 // Open the dialer in a new task instead of as part of Privacy Browser.
1333 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1336 startActivity(dialIntent);
1338 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1340 } else { // Load a system chooser to select an app that can handle the URL.
1341 // Open an app that can handle the URL.
1342 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1344 // Add the URL to the intent.
1345 genericIntent.setData(Uri.parse(url));
1347 // List all apps that can handle the URL instead of just opening the first one.
1348 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1350 // Open the app in a new task instead of as part of Privacy Browser.
1351 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1353 // Start the app or display a snackbar if no app is available to handle the URL.
1355 startActivity(genericIntent);
1356 } catch (ActivityNotFoundException exception) {
1357 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1360 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1365 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1366 @SuppressWarnings("deprecation")
1368 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1369 // Create an empty web resource response to be used if the resource request is blocked.
1370 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1372 // Reset the whitelist results tracker.
1373 whiteListResultStringArray = null;
1375 // Initialize the third party request tracker.
1376 boolean isThirdPartyRequest = false;
1378 // Initialize the current domain string.
1379 String currentDomain = "";
1381 // Nobody is happy when comparing null strings.
1382 if (!(formattedUrlString == null) && !(url == null)) {
1383 // Get the domain strings to URIs.
1384 Uri currentDomainUri = Uri.parse(formattedUrlString);
1385 Uri requestDomainUri = Uri.parse(url);
1387 // Get the domain host names.
1388 String currentBaseDomain = currentDomainUri.getHost();
1389 String requestBaseDomain = requestDomainUri.getHost();
1391 // Update the current domain variable.
1392 currentDomain = currentBaseDomain;
1394 // Only compare the current base domain and the request base domain if neither is null.
1395 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1396 // Determine the current base domain.
1397 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1398 // Remove the first subdomain.
1399 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1402 // Determine the request base domain.
1403 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1404 // Remove the first subdomain.
1405 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1408 // Update the third party request tracker.
1409 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1413 // Block third-party requests if enabled.
1414 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1415 // Increment the blocked requests counters.
1417 thirdPartyBlockedRequests++;
1419 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1420 activity.runOnUiThread(() -> {
1421 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1422 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1423 blockAllThirdPartyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1426 // Add the request to the log.
1427 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1429 // Return an empty web resource response.
1430 return emptyWebResourceResponse;
1433 // Check UltraPrivacy if it is enabled.
1434 if (ultraPrivacyEnabled) {
1435 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1436 // Increment the blocked requests counters.
1438 ultraPrivacyBlockedRequests++;
1440 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1441 activity.runOnUiThread(() -> {
1442 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1443 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1444 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1447 // The resource request was blocked. Return an empty web resource response.
1448 return emptyWebResourceResponse;
1451 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1452 if (whiteListResultStringArray != null) {
1453 // Add a whitelist entry to the resource requests array.
1454 resourceRequests.add(whiteListResultStringArray);
1456 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1461 // Check EasyList if it is enabled.
1462 if (easyListEnabled) {
1463 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1464 // Increment the blocked requests counters.
1466 easyListBlockedRequests++;
1468 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1469 activity.runOnUiThread(() -> {
1470 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1471 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1472 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1475 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1476 whiteListResultStringArray = null;
1478 // The resource request was blocked. Return an empty web resource response.
1479 return emptyWebResourceResponse;
1483 // Check EasyPrivacy if it is enabled.
1484 if (easyPrivacyEnabled) {
1485 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1486 // Increment the blocked requests counters.
1488 easyPrivacyBlockedRequests++;
1490 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1491 activity.runOnUiThread(() -> {
1492 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1493 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1494 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1497 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1498 whiteListResultStringArray = null;
1500 // The resource request was blocked. Return an empty web resource response.
1501 return emptyWebResourceResponse;
1505 // Check Fanboy’s Annoyance List if it is enabled.
1506 if (fanboysAnnoyanceListEnabled) {
1507 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1508 // Increment the blocked requests counters.
1510 fanboysAnnoyanceListBlockedRequests++;
1512 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1513 activity.runOnUiThread(() -> {
1514 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1515 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1516 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1519 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1520 whiteListResultStringArray = null;
1522 // The resource request was blocked. Return an empty web resource response.
1523 return emptyWebResourceResponse;
1525 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1526 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1527 // Increment the blocked requests counters.
1529 fanboysSocialBlockingListBlockedRequests++;
1531 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1532 activity.runOnUiThread(() -> {
1533 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1534 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1535 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1538 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1539 whiteListResultStringArray = null;
1541 // The resource request was blocked. Return an empty web resource response.
1542 return emptyWebResourceResponse;
1546 // Add the request to the log because it hasn't been processed by any of the previous checks.
1547 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1548 resourceRequests.add(whiteListResultStringArray);
1549 } else { // The request didn't match any blocklist entry. Log it as a default request.
1550 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1553 // The resource request has not been blocked. `return null` loads the requested resource.
1557 // Handle HTTP authentication requests.
1559 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1560 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1561 httpAuthHandler = handler;
1563 // Display the HTTP authentication dialog.
1564 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1565 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1568 // Update the URL in urlTextBox when the page starts to load.
1570 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1571 // Reset the list of resource requests.
1572 resourceRequests.clear();
1574 // Initialize the counters for requests blocked by each blocklist.
1575 blockedRequests = 0;
1576 easyListBlockedRequests = 0;
1577 easyPrivacyBlockedRequests = 0;
1578 fanboysAnnoyanceListBlockedRequests = 0;
1579 fanboysSocialBlockingListBlockedRequests = 0;
1580 ultraPrivacyBlockedRequests = 0;
1581 thirdPartyBlockedRequests = 0;
1583 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1585 mainWebView.setVisibility(View.INVISIBLE);
1588 // Hide the keyboard. `0` indicates no additional flags.
1589 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1591 // Check to see if Privacy Browser is waiting on Orbot.
1592 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1593 // 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.
1594 formattedUrlString = url;
1596 // Display the formatted URL text.
1597 urlTextBox.setText(formattedUrlString);
1599 // Apply text highlighting to `urlTextBox`.
1602 // Apply any custom domain settings if the URL was loaded by navigating history.
1603 if (navigatingHistory) {
1604 // Apply the domain settings.
1605 boolean userAgentChanged = applyDomainSettings(url, true, false);
1607 // Reset `navigatingHistory`.
1608 navigatingHistory = false;
1610 // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
1611 if (userAgentChanged) {
1612 loadUrl(formattedUrlString);
1616 // 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.
1617 urlIsLoading = true;
1619 // Replace Refresh with Stop if the menu item has been created. (The WebView typically begins loading before the menu items are instantiated.)
1620 if (refreshMenuItem != null) {
1622 refreshMenuItem.setTitle(R.string.stop);
1624 // If the icon is displayed in the AppBar, set it according to the theme.
1625 if (displayAdditionalAppBarIcons) {
1627 refreshMenuItem.setIcon(R.drawable.close_dark);
1629 refreshMenuItem.setIcon(R.drawable.close_light);
1636 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1638 public void onPageFinished(WebView view, String url) {
1639 // Reset the wide view port if it has been turned off by the waiting for Orbot message.
1640 if (!waitingForOrbot) {
1641 mainWebView.getSettings().setUseWideViewPort(true);
1644 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1645 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1646 cookieManager.flush();
1649 // Update the Refresh menu item if it has been created.
1650 if (refreshMenuItem != null) {
1651 // Reset the Refresh title.
1652 refreshMenuItem.setTitle(R.string.refresh);
1654 // If the icon is displayed in the AppBar, reset it according to the theme.
1655 if (displayAdditionalAppBarIcons) {
1657 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1659 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1664 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1665 urlIsLoading = false;
1667 // Clear the cache and history if Incognito Mode is enabled.
1668 if (incognitoModeEnabled) {
1669 // Clear the cache. `true` includes disk files.
1670 mainWebView.clearCache(true);
1672 // Clear the back/forward history.
1673 mainWebView.clearHistory();
1675 // Manually delete cache folders.
1677 // Delete the main cache directory.
1678 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1680 // Delete the secondary `Service Worker` cache directory.
1681 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1682 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1683 } catch (IOException e) {
1684 // Do nothing if an error is thrown.
1688 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1689 if (!waitingForOrbot) {
1690 // Check to see if `WebView` has set `url` to be `about:blank`.
1691 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1692 // Set `formattedUrlString` to `""`.
1693 formattedUrlString = "";
1695 urlTextBox.setText(formattedUrlString);
1697 // Request focus for `urlTextBox`.
1698 urlTextBox.requestFocus();
1700 // Display the keyboard.
1701 inputMethodManager.showSoftInput(urlTextBox, 0);
1703 // Apply the domain settings. This clears any settings from the previous domain.
1704 applyDomainSettings(formattedUrlString, true, false);
1705 } else { // `WebView` has loaded a webpage.
1706 // Set `formattedUrlString`.
1707 formattedUrlString = url;
1709 // Only update `urlTextBox` if the user is not typing in it.
1710 if (!urlTextBox.hasFocus()) {
1711 // Display the formatted URL text.
1712 urlTextBox.setText(formattedUrlString);
1714 // Apply text highlighting to `urlTextBox`.
1719 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1720 sslCertificate = mainWebView.getCertificate();
1722 // 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.
1723 // Also ignore if changes in the user agent causes an error while navigating history.
1724 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate && navigatingHistory) {
1725 // Initialize the current SSL certificate variables.
1726 String currentWebsiteIssuedToCName = "";
1727 String currentWebsiteIssuedToOName = "";
1728 String currentWebsiteIssuedToUName = "";
1729 String currentWebsiteIssuedByCName = "";
1730 String currentWebsiteIssuedByOName = "";
1731 String currentWebsiteIssuedByUName = "";
1732 Date currentWebsiteSslStartDate = null;
1733 Date currentWebsiteSslEndDate = null;
1736 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1737 if (sslCertificate != null) {
1738 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1739 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1740 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1741 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1742 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1743 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1744 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1745 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1748 // 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`.
1749 String currentWebsiteSslStartDateString = "";
1750 String currentWebsiteSslEndDateString = "";
1751 String pinnedDomainSslStartDateString = "";
1752 String pinnedDomainSslEndDateString = "";
1754 // Convert the `Dates` to `Strings` if they are not `null`.
1755 if (currentWebsiteSslStartDate != null) {
1756 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1759 if (currentWebsiteSslEndDate != null) {
1760 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1763 if (pinnedDomainSslStartDate != null) {
1764 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1767 if (pinnedDomainSslEndDate != null) {
1768 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1771 // Check to see if the pinned SSL certificate matches the current website certificate.
1772 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1773 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1774 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1775 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1776 // The pinned SSL certificate doesn't match the current domain certificate.
1777 //Display the pinned SSL certificate mismatch `AlertDialog`.
1778 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1779 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1785 // Handle SSL Certificate errors.
1787 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1788 // Get the current website SSL certificate.
1789 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1791 // Extract the individual pieces of information from the current website SSL certificate.
1792 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1793 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1794 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1795 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1796 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1797 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1798 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1799 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1801 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1802 if (pinnedDomainSslCertificate &&
1803 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1804 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1805 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1806 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1807 // An SSL certificate is pinned and matches the current domain certificate.
1808 // Proceed to the website without displaying an error.
1810 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1811 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1812 sslErrorHandler = handler;
1814 // Display the SSL error `AlertDialog`.
1815 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1816 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1821 // Load the website if not waiting for Orbot to connect.
1822 if (!waitingForOrbot) {
1823 loadUrl(formattedUrlString);
1828 protected void onNewIntent(Intent intent) {
1829 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1832 // Check to see if the intent contains a new URL.
1833 if (intent.getData() != null) {
1834 // Get the intent data.
1835 final Uri intentUriData = intent.getData();
1837 // Load the website.
1838 loadUrl(intentUriData.toString());
1840 // Close the navigation drawer if it is open.
1841 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1842 drawerLayout.closeDrawer(GravityCompat.START);
1845 // Close the bookmarks drawer if it is open.
1846 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1847 drawerLayout.closeDrawer(GravityCompat.END);
1850 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1851 mainWebView.requestFocus();
1856 public void onRestart() {
1857 // Run the default commands.
1860 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1861 if (proxyThroughOrbot) {
1862 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1863 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1865 // Send the intent to the Orbot package.
1866 orbotIntent.setPackage("org.torproject.android");
1869 sendBroadcast(orbotIntent);
1872 // Apply the app settings if returning from the Settings activity..
1873 if (reapplyAppSettingsOnRestart) {
1874 // Apply the app settings.
1877 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1878 if (reloadOnRestart) {
1879 // Reload `mainWebView`.
1880 mainWebView.reload();
1882 // Reset `reloadOnRestartBoolean`.
1883 reloadOnRestart = false;
1886 // Reset the return from settings flag.
1887 reapplyAppSettingsOnRestart = false;
1890 // Apply the domain settings if returning from the Domains activity.
1891 if (reapplyDomainSettingsOnRestart) {
1892 // Reapply the domain settings.
1893 applyDomainSettings(formattedUrlString, false, true);
1895 // Reset `reapplyDomainSettingsOnRestart`.
1896 reapplyDomainSettingsOnRestart = false;
1899 // Load the URL on restart to apply changes to night mode.
1900 if (loadUrlOnRestart) {
1901 // Load the current `formattedUrlString`.
1902 loadUrl(formattedUrlString);
1904 // Reset `loadUrlOnRestart.
1905 loadUrlOnRestart = false;
1908 // Update the bookmarks drawer if returning from the Bookmarks activity.
1909 if (restartFromBookmarksActivity) {
1910 // Close the bookmarks drawer.
1911 drawerLayout.closeDrawer(GravityCompat.END);
1913 // Reload the bookmarks drawer.
1914 loadBookmarksFolder();
1916 // Reset `restartFromBookmarksActivity`.
1917 restartFromBookmarksActivity = false;
1920 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1921 updatePrivacyIcons(true);
1924 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1926 public void onResume() {
1927 // Run the default commands.
1930 // Resume JavaScript (if enabled).
1931 mainWebView.resumeTimers();
1933 // Resume `mainWebView`.
1934 mainWebView.onResume();
1936 // Resume the adView for the free flavor.
1937 if (BuildConfig.FLAVOR.contentEquals("free")) {
1939 AdHelper.resumeAd(findViewById(R.id.adview));
1942 // Display a message to the user if waiting for Orbot.
1943 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1944 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
1945 mainWebView.getSettings().setUseWideViewPort(false);
1947 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1948 mainWebView.loadData(waitingForOrbotHtmlString, "text/html", null);
1951 if (displayingFullScreenVideo) {
1952 // Remove the translucent overlays.
1953 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1955 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1956 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1958 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1959 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1960 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1962 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1967 public void onPause() {
1968 // Run the default commands.
1971 // Pause `mainWebView`.
1972 mainWebView.onPause();
1974 // Stop all JavaScript.
1975 mainWebView.pauseTimers();
1977 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1978 if (BuildConfig.FLAVOR.contentEquals("free")) {
1980 AdHelper.pauseAd(findViewById(R.id.adview));
1985 public void onDestroy() {
1986 // Unregister the Orbot status broadcast receiver.
1987 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1989 // Close the bookmarks cursor and database.
1990 bookmarksCursor.close();
1991 bookmarksDatabaseHelper.close();
1993 // Run the default commands.
1998 public boolean onCreateOptionsMenu(Menu menu) {
1999 // Inflate the menu; this adds items to the action bar if it is present.
2000 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
2002 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
2005 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
2006 updatePrivacyIcons(false);
2008 // Get handles for the menu items.
2009 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2010 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2011 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2012 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
2013 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
2014 refreshMenuItem = menu.findItem(R.id.refresh);
2015 blocklistsMenuItem = menu.findItem(R.id.blocklists);
2016 easyListMenuItem = menu.findItem(R.id.easylist);
2017 easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
2018 fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
2019 fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
2020 ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
2021 blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
2022 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
2024 // Only display third-party cookies if API >= 21
2025 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
2027 // Only display the form data menu items if the API < 26.
2028 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
2029 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
2031 // Only show Ad Consent if this is the free flavor.
2032 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
2034 // Get the shared preference values.
2035 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2037 // Get the status of the additional AppBar icons.
2038 displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
2040 // 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.
2041 if (displayAdditionalAppBarIcons) {
2042 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2043 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2044 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
2045 } else { //Do not display the additional icons.
2046 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2047 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2048 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2051 // Replace Refresh with Stop if a URL is already loading.
2054 refreshMenuItem.setTitle(R.string.stop);
2056 // If the icon is displayed in the AppBar, set it according to the theme.
2057 if (displayAdditionalAppBarIcons) {
2059 refreshMenuItem.setIcon(R.drawable.close_dark);
2061 refreshMenuItem.setIcon(R.drawable.close_light);
2070 public boolean onPrepareOptionsMenu(Menu menu) {
2071 // Get handles for the menu items.
2072 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2073 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2074 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2075 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2076 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
2077 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2078 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2079 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2080 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
2081 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2082 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
2083 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2084 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
2085 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
2087 // Set the text for the domain menu item.
2088 if (domainSettingsApplied) {
2089 addOrEditDomain.setTitle(R.string.edit_domain_settings);
2091 addOrEditDomain.setTitle(R.string.add_domain_settings);
2094 // Set the status of the menu item checkboxes.
2095 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2096 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2097 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2098 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
2099 easyListMenuItem.setChecked(easyListEnabled);
2100 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
2101 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
2102 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
2103 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
2104 blockAllThirdPartyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
2105 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
2106 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2107 nightModeMenuItem.setChecked(nightMode);
2108 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
2110 // Enable third-party cookies if first-party cookies are enabled.
2111 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2113 // Enable DOM Storage if JavaScript is enabled.
2114 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2116 // Enable Clear Cookies if there are any.
2117 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2119 // Get a count of the number of files in the Local Storage directory.
2120 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2121 int localStorageDirectoryNumberOfFiles = 0;
2122 if (localStorageDirectory.exists()) {
2123 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2126 // Get a count of the number of files in the IndexedDB directory.
2127 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2128 int indexedDBDirectoryNumberOfFiles = 0;
2129 if (indexedDBDirectory.exists()) {
2130 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2133 // Enable Clear DOM Storage if there is any.
2134 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2136 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
2137 if (Build.VERSION.SDK_INT < 26) {
2138 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2139 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2141 // Disable clear form data because it is not supported on current version of Android.
2142 clearFormDataMenuItem.setEnabled(false);
2145 // Enable Clear Data if any of the submenu items are enabled.
2146 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2148 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2149 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2151 // Initialize the display names for the blocklists with the number of blocked requests.
2152 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
2153 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2154 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2155 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2156 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2157 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2158 blockAllThirdPartyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2160 // Get the current user agent.
2161 String currentUserAgent = mainWebView.getSettings().getUserAgentString();
2163 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
2164 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
2165 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
2166 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
2167 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
2168 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
2169 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
2170 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
2171 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
2172 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
2173 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
2174 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
2175 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
2176 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
2177 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
2178 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
2179 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
2180 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
2181 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
2182 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
2183 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
2184 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
2185 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
2186 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
2187 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
2188 } else { // Custom user agent.
2189 menu.findItem(R.id.user_agent_custom).setChecked(true);
2192 // Initialize font size variables.
2193 int fontSize = mainWebView.getSettings().getTextZoom();
2194 String fontSizeTitle;
2195 MenuItem selectedFontSizeMenuItem;
2197 // Prepare the font size title and current size menu item.
2200 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2201 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2205 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2206 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2210 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2211 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2215 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2216 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2220 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2221 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2225 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2226 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2230 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2231 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2235 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2236 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2240 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2241 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2245 // Set the font size title and select the current size menu item.
2246 fontSizeMenuItem.setTitle(fontSizeTitle);
2247 selectedFontSizeMenuItem.setChecked(true);
2249 // Run all the other default commands.
2250 super.onPrepareOptionsMenu(menu);
2252 // Display the menu.
2257 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2258 @SuppressLint("SetJavaScriptEnabled")
2259 // removeAllCookies is deprecated, but it is required for API < 21.
2260 @SuppressWarnings("deprecation")
2261 public boolean onOptionsItemSelected(MenuItem menuItem) {
2262 // Get the selected menu item ID.
2263 int menuItemId = menuItem.getItemId();
2265 // Set the commands that relate to the menu entries.
2266 switch (menuItemId) {
2267 case R.id.toggle_javascript:
2268 // Switch the status of javaScriptEnabled.
2269 javaScriptEnabled = !javaScriptEnabled;
2271 // Apply the new JavaScript status.
2272 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2274 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2275 updatePrivacyIcons(true);
2277 // Display a `Snackbar`.
2278 if (javaScriptEnabled) { // JavaScrip is enabled.
2279 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2280 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2281 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2282 } else { // Privacy mode.
2283 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2286 // Reload the WebView.
2287 mainWebView.reload();
2290 case R.id.add_or_edit_domain:
2291 if (domainSettingsApplied) { // Edit the current domain settings.
2292 // Reapply the domain settings on returning to `MainWebViewActivity`.
2293 reapplyDomainSettingsOnRestart = true;
2294 currentDomainName = "";
2296 // Create an intent to launch the domains activity.
2297 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2299 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2300 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2301 domainsIntent.putExtra("closeOnBack", true);
2304 startActivity(domainsIntent);
2305 } else { // Add a new domain.
2306 // Apply the new domain settings on returning to `MainWebViewActivity`.
2307 reapplyDomainSettingsOnRestart = true;
2308 currentDomainName = "";
2310 // Get the current domain
2311 Uri currentUri = Uri.parse(formattedUrlString);
2312 String currentDomain = currentUri.getHost();
2314 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2315 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2317 // Create the domain and store the database ID.
2318 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2320 // Create an intent to launch the domains activity.
2321 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2323 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2324 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2325 domainsIntent.putExtra("closeOnBack", true);
2328 startActivity(domainsIntent);
2332 case R.id.toggle_first_party_cookies:
2333 // Switch the status of firstPartyCookiesEnabled.
2334 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2336 // Update the menu checkbox.
2337 menuItem.setChecked(firstPartyCookiesEnabled);
2339 // Apply the new cookie status.
2340 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2342 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2343 updatePrivacyIcons(true);
2345 // Display a `Snackbar`.
2346 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2347 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2348 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2349 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2350 } else { // Privacy mode.
2351 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2354 // Reload the WebView.
2355 mainWebView.reload();
2358 case R.id.toggle_third_party_cookies:
2359 if (Build.VERSION.SDK_INT >= 21) {
2360 // Switch the status of thirdPartyCookiesEnabled.
2361 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2363 // Update the menu checkbox.
2364 menuItem.setChecked(thirdPartyCookiesEnabled);
2366 // Apply the new cookie status.
2367 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2369 // Display a `Snackbar`.
2370 if (thirdPartyCookiesEnabled) {
2371 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2373 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2376 // Reload the WebView.
2377 mainWebView.reload();
2378 } // Else do nothing because SDK < 21.
2381 case R.id.toggle_dom_storage:
2382 // Switch the status of domStorageEnabled.
2383 domStorageEnabled = !domStorageEnabled;
2385 // Update the menu checkbox.
2386 menuItem.setChecked(domStorageEnabled);
2388 // Apply the new DOM Storage status.
2389 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2391 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2392 updatePrivacyIcons(true);
2394 // Display a `Snackbar`.
2395 if (domStorageEnabled) {
2396 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2398 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2401 // Reload the WebView.
2402 mainWebView.reload();
2405 // Form data can be removed once the minimum API >= 26.
2406 case R.id.toggle_save_form_data:
2407 // Switch the status of saveFormDataEnabled.
2408 saveFormDataEnabled = !saveFormDataEnabled;
2410 // Update the menu checkbox.
2411 menuItem.setChecked(saveFormDataEnabled);
2413 // Apply the new form data status.
2414 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2416 // Display a `Snackbar`.
2417 if (saveFormDataEnabled) {
2418 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2420 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2423 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2424 updatePrivacyIcons(true);
2426 // Reload the WebView.
2427 mainWebView.reload();
2430 case R.id.clear_cookies:
2431 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2432 .setAction(R.string.undo, v -> {
2433 // Do nothing because everything will be handled by `onDismissed()` below.
2435 .addCallback(new Snackbar.Callback() {
2437 public void onDismissed(Snackbar snackbar, int event) {
2439 // The user pushed the `Undo` button.
2440 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2444 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2446 // `cookieManager.removeAllCookie()` varies by SDK.
2447 if (Build.VERSION.SDK_INT < 21) {
2448 cookieManager.removeAllCookie();
2450 // `null` indicates no callback.
2451 cookieManager.removeAllCookies(null);
2459 case R.id.clear_dom_storage:
2460 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2461 .setAction(R.string.undo, v -> {
2462 // Do nothing because everything will be handled by `onDismissed()` below.
2464 .addCallback(new Snackbar.Callback() {
2466 public void onDismissed(Snackbar snackbar, int event) {
2468 // The user pushed the `Undo` button.
2469 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2473 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2475 // Delete the DOM Storage.
2476 WebStorage webStorage = WebStorage.getInstance();
2477 webStorage.deleteAllData();
2479 // Initialize a handler to manually delete the DOM storage files and directories.
2480 Handler deleteDomStorageHandler = new Handler();
2482 // Setup a runnable to manually delete the DOM storage files and directories.
2483 Runnable deleteDomStorageRunnable = () -> {
2485 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2486 privacyBrowserRuntime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2488 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2489 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2490 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2491 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2492 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2493 } catch (IOException e) {
2494 // Do nothing if an error is thrown.
2498 // Manually delete the DOM storage files after 200 milliseconds.
2499 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
2506 // Form data can be remove once the minimum API >= 26.
2507 case R.id.clear_form_data:
2508 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2509 .setAction(R.string.undo, v -> {
2510 // Do nothing because everything will be handled by `onDismissed()` below.
2512 .addCallback(new Snackbar.Callback() {
2514 public void onDismissed(Snackbar snackbar, int event) {
2516 // The user pushed the `Undo` button.
2517 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2521 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2523 // Delete the form data.
2524 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2525 mainWebViewDatabase.clearFormData();
2533 // Toggle the EasyList status.
2534 easyListEnabled = !easyListEnabled;
2536 // Update the menu checkbox.
2537 menuItem.setChecked(easyListEnabled);
2539 // Reload the main WebView.
2540 mainWebView.reload();
2543 case R.id.easyprivacy:
2544 // Toggle the EasyPrivacy status.
2545 easyPrivacyEnabled = !easyPrivacyEnabled;
2547 // Update the menu checkbox.
2548 menuItem.setChecked(easyPrivacyEnabled);
2550 // Reload the main WebView.
2551 mainWebView.reload();
2554 case R.id.fanboys_annoyance_list:
2555 // Toggle Fanboy's Annoyance List status.
2556 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2558 // Update the menu checkbox.
2559 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2561 // Update the staus of Fanboy's Social Blocking List.
2562 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2563 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2565 // Reload the main WebView.
2566 mainWebView.reload();
2569 case R.id.fanboys_social_blocking_list:
2570 // Toggle Fanboy's Social Blocking List status.
2571 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2573 // Update the menu checkbox.
2574 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2576 // Reload the main WebView.
2577 mainWebView.reload();
2580 case R.id.ultraprivacy:
2581 // Toggle the UltraPrivacy status.
2582 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2584 // Update the menu checkbox.
2585 menuItem.setChecked(ultraPrivacyEnabled);
2587 // Reload the main WebView.
2588 mainWebView.reload();
2591 case R.id.block_all_third_party_requests:
2592 //Toggle the third-party requests blocker status.
2593 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2595 // Update the menu checkbox.
2596 menuItem.setChecked(blockAllThirdPartyRequests);
2598 // Reload the main WebView.
2599 mainWebView.reload();
2602 case R.id.user_agent_privacy_browser:
2603 // Update the user agent.
2604 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
2606 // Reload the WebView.
2607 mainWebView.reload();
2610 case R.id.user_agent_webview_default:
2611 // Update the user agent.
2612 mainWebView.getSettings().setUserAgentString("");
2614 // Reload the WebView.
2615 mainWebView.reload();
2618 case R.id.user_agent_firefox_on_android:
2619 // Update the user agent.
2620 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
2622 // Reload the WebView.
2623 mainWebView.reload();
2626 case R.id.user_agent_chrome_on_android:
2627 // Update the user agent.
2628 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
2630 // Reload the WebView.
2631 mainWebView.reload();
2634 case R.id.user_agent_safari_on_ios:
2635 // Update the user agent.
2636 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
2638 // Reload the WebView.
2639 mainWebView.reload();
2642 case R.id.user_agent_firefox_on_linux:
2643 // Update the user agent.
2644 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
2646 // Reload the WebView.
2647 mainWebView.reload();
2650 case R.id.user_agent_chromium_on_linux:
2651 // Update the user agent.
2652 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
2654 // Reload the WebView.
2655 mainWebView.reload();
2658 case R.id.user_agent_firefox_on_windows:
2659 // Update the user agent.
2660 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
2662 // Reload the WebView.
2663 mainWebView.reload();
2666 case R.id.user_agent_chrome_on_windows:
2667 // Update the user agent.
2668 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
2670 // Reload the WebView.
2671 mainWebView.reload();
2674 case R.id.user_agent_edge_on_windows:
2675 // Update the user agent.
2676 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
2678 // Reload the WebView.
2679 mainWebView.reload();
2682 case R.id.user_agent_internet_explorer_on_windows:
2683 // Update the user agent.
2684 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
2686 // Reload the WebView.
2687 mainWebView.reload();
2690 case R.id.user_agent_safari_on_macos:
2691 // Update the user agent.
2692 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
2694 // Reload the WebView.
2695 mainWebView.reload();
2698 case R.id.user_agent_custom:
2699 // Update the user agent.
2700 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2702 // Reload the WebView.
2703 mainWebView.reload();
2706 case R.id.font_size_twenty_five_percent:
2707 mainWebView.getSettings().setTextZoom(25);
2710 case R.id.font_size_fifty_percent:
2711 mainWebView.getSettings().setTextZoom(50);
2714 case R.id.font_size_seventy_five_percent:
2715 mainWebView.getSettings().setTextZoom(75);
2718 case R.id.font_size_one_hundred_percent:
2719 mainWebView.getSettings().setTextZoom(100);
2722 case R.id.font_size_one_hundred_twenty_five_percent:
2723 mainWebView.getSettings().setTextZoom(125);
2726 case R.id.font_size_one_hundred_fifty_percent:
2727 mainWebView.getSettings().setTextZoom(150);
2730 case R.id.font_size_one_hundred_seventy_five_percent:
2731 mainWebView.getSettings().setTextZoom(175);
2734 case R.id.font_size_two_hundred_percent:
2735 mainWebView.getSettings().setTextZoom(200);
2738 case R.id.swipe_to_refresh:
2739 // Toggle swipe to refresh.
2740 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2743 case R.id.display_images:
2744 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2745 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2746 mainWebView.reload();
2747 } else { // Images are not currently loaded automatically.
2748 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2752 case R.id.night_mode:
2753 // Toggle night mode.
2754 nightMode = !nightMode;
2756 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
2757 if (nightMode) { // Night mode is enabled. Enable JavaScript.
2758 // Update the global variable.
2759 javaScriptEnabled = true;
2760 } else if (domainSettingsApplied) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
2761 // Get the JavaScript preference that was stored the last time domain settings were loaded.
2762 javaScriptEnabled = domainSettingsJavaScriptEnabled;
2763 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
2764 // Get a handle for the shared preference.
2765 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2767 // Get the JavaScript preference.
2768 javaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
2771 // Apply the JavaScript setting to the WebView.
2772 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2774 // Update the privacy icons.
2775 updatePrivacyIcons(false);
2777 // Reload the website.
2778 mainWebView.reload();
2782 // Get a `PrintManager` instance.
2783 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2785 // Convert `mainWebView` to `printDocumentAdapter`.
2786 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2788 // Remove the lint error below that `printManager` might be `null`.
2789 assert printManager != null;
2791 // Print the document. The print attributes are `null`.
2792 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2795 case R.id.view_source:
2796 // Launch the View Source activity.
2797 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2798 startActivity(viewSourceIntent);
2801 case R.id.proxy_through_orbot:
2802 // Toggle the proxy through Orbot variable.
2803 proxyThroughOrbot = !proxyThroughOrbot;
2805 // Apply the proxy through Orbot settings.
2806 applyProxyThroughOrbot(true);
2810 // Setup the share string.
2811 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2813 // Create the share intent.
2814 Intent shareIntent = new Intent(Intent.ACTION_SEND);
2815 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2816 shareIntent.setType("text/plain");
2819 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2822 case R.id.find_on_page:
2823 // Hide the URL app bar.
2824 supportAppBar.setVisibility(View.GONE);
2826 // Show the Find on Page `RelativeLayout`.
2827 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2829 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2830 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2831 findOnPageEditText.postDelayed(() -> {
2832 // Set the focus on `findOnPageEditText`.
2833 findOnPageEditText.requestFocus();
2835 // Display the keyboard. `0` sets no input flags.
2836 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2840 case R.id.add_to_homescreen:
2841 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2842 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2843 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2845 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2849 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2850 // Reload the WebView.
2851 mainWebView.reload();
2852 } else { // The stop button was pushed.
2853 // Stop the loading of the WebView.
2854 mainWebView.stopLoading();
2858 case R.id.ad_consent:
2859 // Display the ad consent dialog.
2860 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2861 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2865 // Don't consume the event.
2866 return super.onOptionsItemSelected(menuItem);
2870 // removeAllCookies is deprecated, but it is required for API < 21.
2871 @SuppressWarnings("deprecation")
2873 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2874 int menuItemId = menuItem.getItemId();
2876 switch (menuItemId) {
2882 if (mainWebView.canGoBack()) {
2883 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2884 formattedUrlString = "";
2886 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2887 navigatingHistory = true;
2889 // Load the previous website in the history.
2890 mainWebView.goBack();
2895 if (mainWebView.canGoForward()) {
2896 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2897 formattedUrlString = "";
2899 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2900 navigatingHistory = true;
2902 // Load the next website in the history.
2903 mainWebView.goForward();
2908 // Get the `WebBackForwardList`.
2909 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2911 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2912 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2913 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2917 // Launch the requests activity.
2918 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2919 startActivity(requestsIntent);
2922 case R.id.downloads:
2923 // Launch the system Download Manager.
2924 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2926 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2927 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2929 startActivity(downloadManagerIntent);
2933 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2934 reapplyDomainSettingsOnRestart = true;
2935 currentDomainName = "";
2937 // Launch the domains activity.
2938 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2939 startActivity(domainsIntent);
2943 // Set the flag to reapply app settings on restart when returning from Settings.
2944 reapplyAppSettingsOnRestart = true;
2946 // Set the flag to reapply the domain settings on restart when returning from Settings.
2947 reapplyDomainSettingsOnRestart = true;
2948 currentDomainName = "";
2950 // Launch the settings activity.
2951 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2952 startActivity(settingsIntent);
2955 case R.id.import_export:
2956 // Launch the import/export activity.
2957 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
2958 startActivity(importExportIntent);
2962 // Launch `GuideActivity`.
2963 Intent guideIntent = new Intent(this, GuideActivity.class);
2964 startActivity(guideIntent);
2968 // Launch `AboutActivity`.
2969 Intent aboutIntent = new Intent(this, AboutActivity.class);
2970 startActivity(aboutIntent);
2973 case R.id.clearAndExit:
2974 // Close the bookmarks cursor and database.
2975 bookmarksCursor.close();
2976 bookmarksDatabaseHelper.close();
2978 // Get a handle for `sharedPreferences`. `this` references the current context.
2979 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2981 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2984 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2985 // The command to remove cookies changed slightly in API 21.
2986 if (Build.VERSION.SDK_INT >= 21) {
2987 cookieManager.removeAllCookies(null);
2989 cookieManager.removeAllCookie();
2992 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2994 // We have to use two commands because `Runtime.exec()` does not like `*`.
2995 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2996 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2997 } catch (IOException e) {
2998 // Do nothing if an error is thrown.
3002 // Clear DOM storage.
3003 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
3004 // Ask `WebStorage` to clear the DOM storage.
3005 WebStorage webStorage = WebStorage.getInstance();
3006 webStorage.deleteAllData();
3008 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
3010 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3011 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
3013 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
3014 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
3015 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
3016 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
3017 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
3018 } catch (IOException e) {
3019 // Do nothing if an error is thrown.
3023 // Clear form data if the API < 26.
3024 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
3025 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
3026 webViewDatabase.clearFormData();
3028 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
3030 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
3031 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
3032 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
3033 } catch (IOException e) {
3034 // Do nothing if an error is thrown.
3039 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
3040 // `true` includes disk files.
3041 mainWebView.clearCache(true);
3043 // Manually delete the cache directories.
3045 // Delete the main cache directory.
3046 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
3048 // Delete the secondary `Service Worker` cache directory.
3049 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
3050 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
3051 } catch (IOException e) {
3052 // Do nothing if an error is thrown.
3056 // Clear SSL certificate preferences.
3057 mainWebView.clearSslPreferences();
3059 // Clear the back/forward history.
3060 mainWebView.clearHistory();
3062 // Clear `formattedUrlString`.
3063 formattedUrlString = null;
3065 // Clear `customHeaders`.
3066 customHeaders.clear();
3068 // Detach all views from `mainWebViewRelativeLayout`.
3069 mainWebViewRelativeLayout.removeAllViews();
3071 // Destroy the internal state of `mainWebView`.
3072 mainWebView.destroy();
3074 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
3075 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
3076 if (clearEverything) {
3078 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
3079 } catch (IOException e) {
3080 // Do nothing if an error is thrown.
3084 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
3085 if (Build.VERSION.SDK_INT >= 21) {
3086 finishAndRemoveTask();
3091 // Remove the terminated program from RAM. The status code is `0`.
3096 // Close the navigation drawer.
3097 drawerLayout.closeDrawer(GravityCompat.START);
3102 public void onPostCreate(Bundle savedInstanceState) {
3103 super.onPostCreate(savedInstanceState);
3105 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
3106 drawerToggle.syncState();
3110 public void onConfigurationChanged(Configuration newConfig) {
3111 super.onConfigurationChanged(newConfig);
3113 // Reload the ad for the free flavor if we not in full screen mode.
3114 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
3115 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3116 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
3119 // `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:
3120 // https://code.google.com/p/android/issues/detail?id=20493#c8
3121 // ActivityCompat.invalidateOptionsMenu(this);
3125 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
3126 // Store the `HitTestResult`.
3127 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
3130 final String imageUrl;
3131 final String linkUrl;
3133 // Get a handle for the `ClipboardManager`.
3134 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
3136 // Remove the lint errors below that `clipboardManager` might be `null`.
3137 assert clipboardManager != null;
3139 switch (hitTestResult.getType()) {
3140 // `SRC_ANCHOR_TYPE` is a link.
3141 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
3142 // Get the target URL.
3143 linkUrl = hitTestResult.getExtra();
3145 // Set the target URL as the title of the `ContextMenu`.
3146 menu.setHeaderTitle(linkUrl);
3148 // Add a Load URL entry.
3149 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
3154 // Add a Copy URL entry.
3155 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
3156 // Save the link URL in a `ClipData`.
3157 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
3159 // Set the `ClipData` as the clipboard's primary clip.
3160 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
3164 // Add a Download URL entry.
3165 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
3166 // Check if the download should be processed by an external app.
3167 if (downloadWithExternalApp) { // Download with an external app.
3168 openUrlWithExternalApp(linkUrl);
3169 } else { // Download with Android's download manager.
3170 // Check to see if the storage permission has already been granted.
3171 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
3172 // Store the variables for future use by `onRequestPermissionsResult()`.
3173 downloadUrl = linkUrl;
3174 downloadContentDisposition = "none";
3175 downloadContentLength = -1;
3177 // Show a dialog if the user has previously denied the permission.
3178 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3179 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
3180 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
3182 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
3183 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3184 } else { // Show the permission request directly.
3185 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
3186 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3188 } else { // The storage permission has already been granted.
3189 // Get a handle for the download file alert dialog.
3190 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
3192 // Show the download file alert dialog.
3193 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3199 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3200 menu.add(R.string.cancel);
3203 case WebView.HitTestResult.EMAIL_TYPE:
3204 // Get the target URL.
3205 linkUrl = hitTestResult.getExtra();
3207 // Set the target URL as the title of the `ContextMenu`.
3208 menu.setHeaderTitle(linkUrl);
3210 // Add a `Write Email` entry.
3211 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
3212 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
3213 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
3215 // Parse the url and set it as the data for the `Intent`.
3216 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
3218 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
3219 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3222 startActivity(emailIntent);
3226 // Add a `Copy Email Address` entry.
3227 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
3228 // Save the email address in a `ClipData`.
3229 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
3231 // Set the `ClipData` as the clipboard's primary clip.
3232 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
3236 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3237 menu.add(R.string.cancel);
3240 // `IMAGE_TYPE` is an image.
3241 case WebView.HitTestResult.IMAGE_TYPE:
3242 // Get the image URL.
3243 imageUrl = hitTestResult.getExtra();
3245 // Set the image URL as the title of the `ContextMenu`.
3246 menu.setHeaderTitle(imageUrl);
3248 // Add a `View Image` entry.
3249 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3254 // Add a `Download Image` entry.
3255 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3256 // Check if the download should be processed by an external app.
3257 if (downloadWithExternalApp) { // Download with an external app.
3258 openUrlWithExternalApp(imageUrl);
3259 } else { // Download with Android's download manager.
3260 // Check to see if the storage permission has already been granted.
3261 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
3262 // Store the image URL for use by `onRequestPermissionResult()`.
3263 downloadImageUrl = imageUrl;
3265 // Show a dialog if the user has previously denied the permission.
3266 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3267 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3268 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3270 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3271 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3272 } else { // Show the permission request directly.
3273 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3274 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3276 } else { // The storage permission has already been granted.
3277 // Get a handle for the download image alert dialog.
3278 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3280 // Show the download image alert dialog.
3281 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3287 // Add a `Copy URL` entry.
3288 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3289 // Save the image URL in a `ClipData`.
3290 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3292 // Set the `ClipData` as the clipboard's primary clip.
3293 clipboardManager.setPrimaryClip(srcImageTypeClipData);
3297 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3298 menu.add(R.string.cancel);
3302 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
3303 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
3304 // Get the image URL.
3305 imageUrl = hitTestResult.getExtra();
3307 // Set the image URL as the title of the `ContextMenu`.
3308 menu.setHeaderTitle(imageUrl);
3310 // Add a `View Image` entry.
3311 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3316 // Add a `Download Image` entry.
3317 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3318 // Check if the download should be processed by an external app.
3319 if (downloadWithExternalApp) { // Download with an external app.
3320 openUrlWithExternalApp(imageUrl);
3321 } else { // Download with Android's download manager.
3322 // Check to see if the storage permission has already been granted.
3323 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
3324 // Store the image URL for use by `onRequestPermissionResult()`.
3325 downloadImageUrl = imageUrl;
3327 // Show a dialog if the user has previously denied the permission.
3328 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3329 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3330 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3332 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3333 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3334 } else { // Show the permission request directly.
3335 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3336 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3338 } else { // The storage permission has already been granted.
3339 // Get a handle for the download image alert dialog.
3340 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3342 // Show the download image alert dialog.
3343 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3349 // Add a `Copy URL` entry.
3350 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3351 // Save the image URL in a `ClipData`.
3352 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3354 // Set the `ClipData` as the clipboard's primary clip.
3355 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3359 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3360 menu.add(R.string.cancel);
3366 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3367 // Get the `EditTexts` from the `dialogFragment`.
3368 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3369 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3371 // Extract the strings from the `EditTexts`.
3372 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3373 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3375 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3376 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3377 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3378 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3380 // Display the new bookmark below the current items in the (0 indexed) list.
3381 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3383 // Create the bookmark.
3384 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3386 // Update `bookmarksCursor` with the current contents of this folder.
3387 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3389 // Update the `ListView`.
3390 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3392 // Scroll to the new bookmark.
3393 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3397 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3398 // Get handles for the views in `dialogFragment`.
3399 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3400 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3401 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3403 // Get new folder name string.
3404 String folderNameString = createFolderNameEditText.getText().toString();
3406 // Get the new folder icon `Bitmap`.
3407 Bitmap folderIconBitmap;
3408 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3409 // Get the default folder icon and convert it to a `Bitmap`.
3410 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3411 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3412 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3413 } else { // Use the `WebView` favorite icon.
3414 folderIconBitmap = favoriteIconBitmap;
3417 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3418 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3419 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3420 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3422 // Move all the bookmarks down one in the display order.
3423 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3424 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3425 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3428 // Create the folder, which will be placed at the top of the `ListView`.
3429 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3431 // Update `bookmarksCursor` with the current contents of this folder.
3432 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3434 // Update the `ListView`.
3435 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3437 // Scroll to the new folder.
3438 bookmarksListView.setSelection(0);
3442 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3443 // Get the shortcut name.
3444 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3445 String shortcutNameString = shortcutNameEditText.getText().toString();
3447 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3448 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3450 // Setup the shortcut intent.
3451 Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
3452 shortcutIntent.setData(Uri.parse(formattedUrlString));
3454 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3455 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3457 // Add the required fields to the shortcut info builder.
3458 shortcutInfoBuilder.setIcon(favoriteIcon);
3459 shortcutInfoBuilder.setIntent(shortcutIntent);
3460 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3462 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3463 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3467 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3468 switch (downloadType) {
3469 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3470 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3471 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3474 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3475 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3476 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3482 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
3483 switch (requestCode) {
3484 case DOWNLOAD_FILE_REQUEST_CODE:
3485 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3486 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3488 // On API 23, displaying the fragment must be delayed or the app will crash.
3489 if (Build.VERSION.SDK_INT == 23) {
3490 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3492 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3495 // Reset the download variables.
3497 downloadContentDisposition = "";
3498 downloadContentLength = 0;
3501 case DOWNLOAD_IMAGE_REQUEST_CODE:
3502 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3503 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3505 // On API 23, displaying the fragment must be delayed or the app will crash.
3506 if (Build.VERSION.SDK_INT == 23) {
3507 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3509 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3512 // Reset the image URL variable.
3513 downloadImageUrl = "";
3519 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3520 // Download the image if it has an HTTP or HTTPS URI.
3521 if (imageUrl.startsWith("http")) {
3522 // Get a handle for the system `DOWNLOAD_SERVICE`.
3523 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3525 // Parse `imageUrl`.
3526 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3528 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3529 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3530 if (firstPartyCookiesEnabled) {
3531 // Get the cookies for `imageUrl`.
3532 String cookies = cookieManager.getCookie(imageUrl);
3534 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3535 downloadRequest.addRequestHeader("Cookie", cookies);
3538 // Get the file name from the dialog fragment.
3539 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3540 String imageName = downloadImageNameEditText.getText().toString();
3542 // Specify the download location.
3543 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3544 // Download to the public download directory.
3545 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3546 } else { // External write permission denied.
3547 // Download to the app's external download directory.
3548 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3551 // Allow `MediaScanner` to index the download if it is a media file.
3552 downloadRequest.allowScanningByMediaScanner();
3554 // Add the URL as the description for the download.
3555 downloadRequest.setDescription(imageUrl);
3557 // Show the download notification after the download is completed.
3558 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3560 // Remove the lint warning below that `downloadManager` might be `null`.
3561 assert downloadManager != null;
3563 // Initiate the download.
3564 downloadManager.enqueue(downloadRequest);
3565 } else { // The image is not an HTTP or HTTPS URI.
3566 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3571 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3572 // Download the file if it has an HTTP or HTTPS URI.
3573 if (downloadUrl.startsWith("http")) {
3574 // Get a handle for the system `DOWNLOAD_SERVICE`.
3575 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3577 // Parse `downloadUrl`.
3578 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3580 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3581 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3582 if (firstPartyCookiesEnabled) {
3583 // Get the cookies for `downloadUrl`.
3584 String cookies = cookieManager.getCookie(downloadUrl);
3586 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3587 downloadRequest.addRequestHeader("Cookie", cookies);
3590 // Get the file name from the dialog fragment.
3591 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3592 String fileName = downloadFileNameEditText.getText().toString();
3594 // Specify the download location.
3595 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3596 // Download to the public download directory.
3597 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3598 } else { // External write permission denied.
3599 // Download to the app's external download directory.
3600 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3603 // Allow `MediaScanner` to index the download if it is a media file.
3604 downloadRequest.allowScanningByMediaScanner();
3606 // Add the URL as the description for the download.
3607 downloadRequest.setDescription(downloadUrl);
3609 // Show the download notification after the download is completed.
3610 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3612 // Remove the lint warning below that `downloadManager` might be `null`.
3613 assert downloadManager != null;
3615 // Initiate the download.
3616 downloadManager.enqueue(downloadRequest);
3617 } else { // The download is not an HTTP or HTTPS URI.
3618 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3623 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3624 // Get handles for the views from `dialogFragment`.
3625 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3626 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3627 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3629 // Store the bookmark strings.
3630 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3631 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3633 // Update the bookmark.
3634 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3635 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3636 } else { // Update the bookmark using the `WebView` favorite icon.
3637 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3638 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3639 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3640 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3642 // Update the bookmark and the favorite icon.
3643 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3646 // Update `bookmarksCursor` with the current contents of this folder.
3647 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3649 // Update the `ListView`.
3650 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3654 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3655 // Get handles for the views from `dialogFragment`.
3656 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3657 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3658 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3659 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3661 // Get the new folder name.
3662 String newFolderNameString = editFolderNameEditText.getText().toString();
3664 // Check if the favorite icon has changed.
3665 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3666 // Update the name in the database.
3667 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3668 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3669 // Get the new folder icon `Bitmap`.
3670 Bitmap folderIconBitmap;
3671 if (defaultFolderIconRadioButton.isChecked()) {
3672 // Get the default folder icon and convert it to a `Bitmap`.
3673 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3674 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3675 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3676 } else { // Use the `WebView` favorite icon.
3677 folderIconBitmap = favoriteIconBitmap;
3680 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3681 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3682 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3683 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3685 // Update the folder icon in the database.
3686 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3687 } else { // The folder icon and the name have changed.
3688 // Get the new folder icon `Bitmap`.
3689 Bitmap folderIconBitmap;
3690 if (defaultFolderIconRadioButton.isChecked()) {
3691 // Get the default folder icon and convert it to a `Bitmap`.
3692 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3693 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3694 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3695 } else { // Use the `WebView` favorite icon.
3696 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3699 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3700 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3701 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3702 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3704 // Update the folder name and icon in the database.
3705 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3708 // Update `bookmarksCursor` with the current contents of this folder.
3709 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3711 // Update the `ListView`.
3712 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3716 public void onHttpAuthenticationCancel() {
3717 // Cancel the `HttpAuthHandler`.
3718 httpAuthHandler.cancel();
3722 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3723 // Get handles for the `EditTexts`.
3724 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3725 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3727 // Proceed with the HTTP authentication.
3728 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3731 public void viewSslCertificate(View view) {
3732 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3733 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3734 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3738 public void onSslErrorCancel() {
3739 sslErrorHandler.cancel();
3743 public void onSslErrorProceed() {
3744 sslErrorHandler.proceed();
3748 public void onSslMismatchBack() {
3749 if (mainWebView.canGoBack()) { // There is a back page in the history.
3750 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3751 formattedUrlString = "";
3753 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3754 navigatingHistory = true;
3757 mainWebView.goBack();
3758 } else { // There are no pages to go back to.
3759 // Load a blank page
3765 public void onSslMismatchProceed() {
3766 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3767 ignorePinnedSslCertificate = true;
3771 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3772 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3773 formattedUrlString = "";
3775 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3776 navigatingHistory = true;
3778 // Load the history entry.
3779 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3783 public void onClearHistory() {
3784 // Clear the history.
3785 mainWebView.clearHistory();
3788 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3790 public void onBackPressed() {
3791 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3792 // Close the navigation drawer.
3793 drawerLayout.closeDrawer(GravityCompat.START);
3794 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3795 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3796 // close the bookmarks drawer.
3797 drawerLayout.closeDrawer(GravityCompat.END);
3798 } else { // A subfolder is displayed.
3799 // Place the former parent folder in `currentFolder`.
3800 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3802 // Load the new folder.
3803 loadBookmarksFolder();
3806 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3807 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3808 formattedUrlString = "";
3810 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3811 navigatingHistory = true;
3814 mainWebView.goBack();
3815 } else { // There isn't anything to do in Privacy Browser.
3816 // Pass `onBackPressed()` to the system.
3817 super.onBackPressed();
3821 // 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.
3823 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3824 // File uploads only work on API >= 21.
3825 if (Build.VERSION.SDK_INT >= 21) {
3826 // Pass the file to the WebView.
3827 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3831 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3832 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3833 String unformattedUrlString = urlTextBox.getText().toString().trim();
3835 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3836 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3837 // Add `https://` at the beginning if it is missing. Otherwise the app will segfault.
3838 if (!unformattedUrlString.startsWith("http")) {
3839 unformattedUrlString = "https://" + unformattedUrlString;
3842 // Initialize `unformattedUrl`.
3843 URL unformattedUrl = null;
3845 // 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.
3847 unformattedUrl = new URL(unformattedUrlString);
3848 } catch (MalformedURLException e) {
3849 e.printStackTrace();
3852 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3853 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3854 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3855 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3856 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3857 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3860 Uri.Builder formattedUri = new Uri.Builder();
3861 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3863 // Decode `formattedUri` as a `String` in `UTF-8`.
3864 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3865 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3866 // Load a blank string.
3867 formattedUrlString = "";
3868 } else { // Search for the contents of the URL box.
3869 // Sanitize the search input and convert it to a search.
3870 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3872 // Add the base search URL.
3873 formattedUrlString = searchURL + encodedUrlString;
3876 // 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.
3877 urlTextBox.clearFocus();
3880 loadUrl(formattedUrlString);
3883 private void loadUrl(String url) {// Apply any custom domain settings.
3884 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3885 formattedUrlString = url;
3887 // Apply the domain settings.
3888 applyDomainSettings(url, true, false);
3890 // If loading a website, set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3891 urlIsLoading = !url.equals("");
3894 mainWebView.loadUrl(url, customHeaders);
3897 public void findPreviousOnPage(View view) {
3898 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3899 mainWebView.findNext(false);
3902 public void findNextOnPage(View view) {
3903 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3904 mainWebView.findNext(true);
3907 public void closeFindOnPage(View view) {
3908 // Delete the contents of `find_on_page_edittext`.
3909 findOnPageEditText.setText(null);
3911 // Clear the highlighted phrases.
3912 mainWebView.clearMatches();
3914 // Hide the Find on Page `RelativeLayout`.
3915 findOnPageLinearLayout.setVisibility(View.GONE);
3917 // Show the URL app bar.
3918 supportAppBar.setVisibility(View.VISIBLE);
3920 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3921 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3924 private void applyAppSettings() {
3925 // Get a handle for the shared preferences.
3926 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3928 // Store the values from the shared preferences in variables.
3929 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3930 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3931 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3932 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3933 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3934 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3935 downloadWithExternalApp = sharedPreferences.getBoolean("download_with_external_app", false);
3937 // Apply the proxy through Orbot settings.
3938 applyProxyThroughOrbot(false);
3940 // Set Do Not Track status.
3941 if (doNotTrackEnabled) {
3942 customHeaders.put("DNT", "1");
3944 customHeaders.remove("DNT");
3947 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3948 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3949 if (hideSystemBarsOnFullscreen) { // Hide everything.
3950 // Remove the translucent navigation setting if it is currently flagged.
3951 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3953 // Remove the translucent status bar overlay.
3954 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3956 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3957 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3959 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3960 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3961 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3963 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3964 } else { // Hide everything except the status and navigation bars.
3965 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3966 rootCoordinatorLayout.setSystemUiVisibility(0);
3968 // Add the translucent status flag if it is unset.
3969 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3971 if (translucentNavigationBarOnFullscreen) {
3972 // Set the navigation bar to be translucent.
3973 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3975 // Set the navigation bar to be black.
3976 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3979 } else { // Privacy Browser is not in full screen browsing mode.
3980 // 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.
3981 inFullScreenBrowsingMode = false;
3983 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3984 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3988 // Show the `BannerAd` in the free flavor.
3989 if (BuildConfig.FLAVOR.contentEquals("free")) {
3990 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3991 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
3994 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3995 rootCoordinatorLayout.setSystemUiVisibility(0);
3997 // Remove the translucent navigation bar flag if it is set.
3998 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
4000 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
4001 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4003 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
4004 rootCoordinatorLayout.setFitsSystemWindows(true);
4008 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
4009 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
4010 @SuppressWarnings("deprecation")
4011 private boolean applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
4012 // Get the current user agent.
4013 String initialUserAgent = mainWebView.getSettings().getUserAgentString();
4015 // Initialize a variable to track if the user agent changes.
4016 boolean userAgentChanged = false;
4018 // Parse the URL into a URI.
4019 Uri uri = Uri.parse(url);
4021 // Extract the domain from `uri`.
4022 String hostName = uri.getHost();
4024 // Initialize `loadingNewDomainName`.
4025 boolean loadingNewDomainName;
4027 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
4028 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
4029 //noinspection SimplifiableIfStatement
4030 if ((hostName == null) || (currentDomainName == null)) {
4031 loadingNewDomainName = true;
4032 } else { // Determine if `hostName` equals `currentDomainName`.
4033 loadingNewDomainName = !hostName.equals(currentDomainName);
4036 // Strings don't like to be null.
4037 if (hostName == null) {
4041 // 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.
4042 if (loadingNewDomainName) {
4043 // Set the new `hostname` as the `currentDomainName`.
4044 currentDomainName = hostName;
4046 // Reset `ignorePinnedSslCertificate`.
4047 ignorePinnedSslCertificate = false;
4049 // Reset the favorite icon if specified.
4050 if (resetFavoriteIcon) {
4051 favoriteIconBitmap = favoriteIconDefaultBitmap;
4052 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
4055 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
4056 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
4058 // Get a full cursor from `domainsDatabaseHelper`.
4059 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
4061 // Initialize `domainSettingsSet`.
4062 Set<String> domainSettingsSet = new HashSet<>();
4064 // Get the domain name column index.
4065 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
4067 // Populate `domainSettingsSet`.
4068 for (int i = 0; i < domainNameCursor.getCount(); i++) {
4069 // Move `domainsCursor` to the current row.
4070 domainNameCursor.moveToPosition(i);
4072 // Store the domain name in `domainSettingsSet`.
4073 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
4076 // Close `domainNameCursor.
4077 domainNameCursor.close();
4079 // Initialize variables to track if domain settings will be applied and, if so, under which name.
4080 domainSettingsApplied = false;
4081 String domainNameInDatabase = null;
4083 // Check the hostname.
4084 if (domainSettingsSet.contains(hostName)) {
4085 domainSettingsApplied = true;
4086 domainNameInDatabase = hostName;
4089 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
4090 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
4091 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
4092 // Apply the domain settings.
4093 domainSettingsApplied = true;
4095 // Store the applied domain names as it appears in the database.
4096 domainNameInDatabase = "*." + hostName;
4099 // Strip out the lowest subdomain of of the host name.
4100 hostName = hostName.substring(hostName.indexOf(".") + 1);
4104 // Get a handle for the shared preference.
4105 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4107 // Store the general preference information.
4108 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
4109 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
4110 defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value));
4111 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
4112 nightMode = sharedPreferences.getBoolean("night_mode", false);
4113 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
4115 if (domainSettingsApplied) { // The url has custom domain settings.
4116 // Get a cursor for the current host and move it to the first position.
4117 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
4118 currentHostDomainSettingsCursor.moveToFirst();
4120 // Get the settings from the cursor.
4121 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
4122 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
4123 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
4124 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
4125 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
4126 // Form data can be removed once the minimum API >= 26.
4127 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
4128 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
4129 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
4130 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
4131 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
4132 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
4133 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
4134 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
4135 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
4136 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
4137 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
4138 int displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
4139 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
4140 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
4141 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
4142 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
4143 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
4144 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
4145 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
4147 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
4148 switch (nightModeInt) {
4149 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
4153 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
4158 // Store the domain JavaScript status. This is used by the options menu night mode toggle.
4159 domainSettingsJavaScriptEnabled = javaScriptEnabled;
4161 // Enable JavaScript if night mode is enabled.
4163 javaScriptEnabled = true;
4166 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
4167 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
4168 pinnedDomainSslStartDate = null;
4170 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
4173 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
4174 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
4175 pinnedDomainSslEndDate = null;
4177 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
4180 // Close `currentHostDomainSettingsCursor`.
4181 currentHostDomainSettingsCursor.close();
4183 // Apply the domain settings.
4184 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4185 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4186 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4188 // Apply the form data setting if the API < 26.
4189 if (Build.VERSION.SDK_INT < 26) {
4190 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4193 // Apply the font size.
4194 if (fontSize == 0) { // Apply the default font size.
4195 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4196 } else { // Apply the specified font size.
4197 mainWebView.getSettings().setTextZoom(fontSize);
4200 // Set third-party cookies status if API >= 21.
4201 if (Build.VERSION.SDK_INT >= 21) {
4202 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4205 // 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.
4206 // <https://redmine.stoutner.com/issues/160>
4207 if (!urlIsLoading) {
4208 // Set the user agent.
4209 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4210 // Get the array position of the default user agent name.
4211 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4213 // Set the user agent according to the system default.
4214 switch (defaultUserAgentArrayPosition) {
4215 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4216 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4217 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4220 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4221 // Set the user agent to `""`, which uses the default value.
4222 mainWebView.getSettings().setUserAgentString("");
4225 case SETTINGS_CUSTOM_USER_AGENT:
4226 // Set the custom user agent.
4227 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4231 // Get the user agent string from the user agent data array
4232 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4234 } else { // Set the user agent according to the stored name.
4235 // Get the array position of the user agent name.
4236 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4238 switch (userAgentArrayPosition) {
4239 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4240 mainWebView.getSettings().setUserAgentString(userAgentName);
4243 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4244 // Set the user agent to `""`, which uses the default value.
4245 mainWebView.getSettings().setUserAgentString("");
4249 // Get the user agent string from the user agent data array.
4250 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4254 // Store the applied user agent string, which is used in the View Source activity.
4255 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4257 // Update the user agent change tracker.
4258 userAgentChanged = !appliedUserAgentString.equals(initialUserAgent);
4261 // Set swipe to refresh.
4262 switch (swipeToRefreshInt) {
4263 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
4264 // Set swipe to refresh according to the default.
4265 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4268 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
4269 // Enable swipe to refresh.
4270 swipeRefreshLayout.setEnabled(true);
4273 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
4274 // Disable swipe to refresh.
4275 swipeRefreshLayout.setEnabled(false);
4278 // Set the loading of webpage images.
4279 switch (displayWebpageImagesInt) {
4280 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4281 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4284 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4285 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4288 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4289 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4293 // 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.
4295 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4297 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4299 } else { // The new URL does not have custom domain settings. Load the defaults.
4300 // Store the values from `sharedPreferences` in variables.
4301 javaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
4302 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies", false);
4303 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
4304 domStorageEnabled = sharedPreferences.getBoolean("dom_storage", false);
4305 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4306 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
4307 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
4308 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboys_annoyance_list", true);
4309 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboys_social_blocking_list", true);
4310 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
4311 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
4313 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4315 javaScriptEnabled = true;
4318 // Apply the default settings.
4319 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4320 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4321 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4322 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4323 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4325 // Apply the form data setting if the API < 26.
4326 if (Build.VERSION.SDK_INT < 26) {
4327 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4330 // Reset the pinned SSL certificate information.
4331 domainSettingsDatabaseId = -1;
4332 pinnedDomainSslCertificate = false;
4333 pinnedDomainSslIssuedToCNameString = "";
4334 pinnedDomainSslIssuedToONameString = "";
4335 pinnedDomainSslIssuedToUNameString = "";
4336 pinnedDomainSslIssuedByCNameString = "";
4337 pinnedDomainSslIssuedByONameString = "";
4338 pinnedDomainSslIssuedByUNameString = "";
4339 pinnedDomainSslStartDate = null;
4340 pinnedDomainSslEndDate = null;
4342 // Set third-party cookies status if API >= 21.
4343 if (Build.VERSION.SDK_INT >= 21) {
4344 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4347 // 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.
4348 // <https://redmine.stoutner.com/issues/160>
4349 if (!urlIsLoading) {
4350 // Get the array position of the user agent name.
4351 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4353 // Set the user agent.
4354 switch (userAgentArrayPosition) {
4355 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4356 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4357 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4360 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4361 // Set the user agent to `""`, which uses the default value.
4362 mainWebView.getSettings().setUserAgentString("");
4365 case SETTINGS_CUSTOM_USER_AGENT:
4366 // Set the custom user agent.
4367 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4371 // Get the user agent string from the user agent data array
4372 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4375 // Store the applied user agent string, which is used in the View Source activity.
4376 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4378 // Update the user agent change tracker.
4379 userAgentChanged = !appliedUserAgentString.equals(initialUserAgent);
4382 // Set the loading of webpage images.
4383 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4385 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4386 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4389 // Close the domains database helper.
4390 domainsDatabaseHelper.close();
4392 // Update the privacy icons, but only if `mainMenu` has already been populated.
4393 if (mainMenu != null) {
4394 updatePrivacyIcons(true);
4398 // Reload the website if returning from the Domains activity.
4399 if (reloadWebsite) {
4400 mainWebView.reload();
4403 // Return the user agent changed status.
4404 return userAgentChanged;
4407 private void applyProxyThroughOrbot(boolean reloadWebsite) {
4408 // Get a handle for the shared preferences.
4409 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4411 // Get the search preferences.
4412 String homepageString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
4413 String torHomepageString = sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value));
4414 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
4415 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
4416 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
4417 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
4419 // Set the homepage, search, and proxy options.
4420 if (proxyThroughOrbot) { // Set the Tor options.
4421 // Set `torHomepageString` as `homepage`.
4422 homepage = torHomepageString;
4424 // If formattedUrlString is null assign the homepage to it.
4425 if (formattedUrlString == null) {
4426 formattedUrlString = homepage;
4429 // Set the search URL.
4430 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
4431 searchURL = torSearchCustomUrlString;
4432 } else { // Use the string from the pre-built list.
4433 searchURL = torSearchString;
4436 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
4437 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
4439 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
4441 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
4443 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
4446 // Check to see if Orbot is ready.
4447 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4448 // Set `waitingForOrbot`.
4449 waitingForOrbot = true;
4451 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
4452 mainWebView.getSettings().setUseWideViewPort(false);
4454 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
4455 mainWebView.loadData(waitingForOrbotHtmlString, "text/html", null);
4456 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
4457 // Reload the website.
4458 mainWebView.reload();
4460 } else { // Set the non-Tor options.
4461 // Set `homepageString` as `homepage`.
4462 homepage = homepageString;
4464 // If formattedUrlString is null assign the homepage to it.
4465 if (formattedUrlString == null) {
4466 formattedUrlString = homepage;
4469 // Set the search URL.
4470 if (searchString.equals("Custom URL")) { // Get the custom URL string.
4471 searchURL = searchCustomUrlString;
4472 } else { // Use the string from the pre-built list.
4473 searchURL = searchString;
4476 // Reset the proxy to default. The host is `""` and the port is `"0"`.
4477 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
4479 // Set the default `appBar` background. `this` refers to the context.
4481 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
4483 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
4486 // Reset `waitingForOrbot.
4487 waitingForOrbot = false;
4489 // Reload the website if requested.
4490 if (reloadWebsite) {
4491 mainWebView.reload();
4496 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4497 // Get handles for the menu items.
4498 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4499 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4500 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4501 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4503 // Update the privacy icon.
4504 if (javaScriptEnabled) { // JavaScript is enabled.
4505 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4506 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4507 privacyMenuItem.setIcon(R.drawable.warning);
4508 } else { // All the dangerous features are disabled.
4509 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4512 // Update the first-party cookies icon.
4513 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4514 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4515 } else { // First-party cookies are disabled.
4517 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4519 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4523 // Update the DOM storage icon.
4524 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4525 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4526 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4528 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4530 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4532 } else { // JavaScript is disabled, so DOM storage is ghosted.
4534 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4536 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4540 // Update the refresh icon.
4542 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4544 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4547 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4548 if (runInvalidateOptionsMenu) {
4549 invalidateOptionsMenu();
4553 private void openUrlWithExternalApp(String url) {
4554 // Create a download intent. Not specifying the action type will display the maximum number of options.
4555 Intent downloadIntent = new Intent();
4557 // Set the URI and the mime type. `"*/*"` will display the maximum number of options.
4558 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
4560 // Flag the intent to open in a new task.
4561 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4563 // Show the chooser.
4564 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4567 private void highlightUrlText() {
4568 // Get the URL string.
4569 String urlString = urlTextBox.getText().toString();
4571 // Get the index of the `/` immediately after the domain name.
4572 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4574 // Create a base URL string.
4577 // Get the base URL.
4578 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4579 // Get the base URL.
4580 baseUrl = urlString.substring(0, endOfDomainName);
4581 } else { // There are no characters after the base URL.
4582 // Set the base URL to be the entire URL string.
4583 baseUrl = urlString;
4586 // Get the index of the last `.` in the domain.
4587 int lastDotIndex = baseUrl.lastIndexOf(".");
4589 // Get the index of the penultimate `.` in the domain.
4590 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4592 // Markup the beginning of the URL.
4593 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4594 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4596 // De-emphasize subdomains.
4597 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4598 urlTextBox.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4600 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4601 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4602 // De-emphasize the protocol and the additional subdomains.
4603 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4604 } else { // There is only one subdomain in the domain name.
4605 // De-emphasize only the protocol.
4606 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4610 // De-emphasize the text after the domain name.
4611 if (endOfDomainName > 0) {
4612 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4616 private void loadBookmarksFolder() {
4617 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4618 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4620 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4621 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4623 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4624 // Inflate the individual item layout. `false` does not attach it to the root.
4625 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4629 public void bindView(View view, Context context, Cursor cursor) {
4630 // Get handles for the views.
4631 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4632 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4634 // Get the favorite icon byte array from the cursor.
4635 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4637 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4638 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4640 // Display the bitmap in `bookmarkFavoriteIcon`.
4641 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4643 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4644 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4645 bookmarkNameTextView.setText(bookmarkNameString);
4647 // Make the font bold for folders.
4648 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4649 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4650 } else { // Reset the font to default for normal bookmarks.
4651 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4656 // Populate the `ListView` with the adapter.
4657 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4659 // Set the bookmarks drawer title.
4660 if (currentBookmarksFolder.isEmpty()) {
4661 bookmarksTitleTextView.setText(R.string.bookmarks);
4663 bookmarksTitleTextView.setText(currentBookmarksFolder);