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()`, and `loadUrlFromTextBox()`.
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()` and `onResume()`.
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;
206 int easyListBlockedRequests;
207 int easyPrivacyBlockedRequests;
208 int fanboysAnnoyanceListBlockedRequests;
209 int fanboysSocialBlockingListBlockedRequests;
210 int ultraPrivacyBlockedRequests;
211 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()`, and `applyAppSettings()`.
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 `setDisplayWebpageImages()`.
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()` and `applyDomainSettings()`.
332 private boolean nightMode;
334 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
335 private boolean displayWebpageImagesBoolean;
337 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
338 private String homepage;
340 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
341 private String searchURL;
343 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
344 private Menu mainMenu;
346 // `refreshMenuItem` is used in `onCreate()` and `onCreateOptionsMenu()`.
347 private MenuItem refreshMenuItem;
349 // The blocklist menu items are used in `onCreate()`, `onCreateOptionsMenu()`, and `onPrepareOptionsMenu()`.
350 private MenuItem blocklistsMenuItem;
351 private MenuItem easyListMenuItem;
352 private MenuItem easyPrivacyMenuItem;
353 private MenuItem fanboysAnnoyanceListMenuItem;
354 private MenuItem fanboysSocialBlockingListMenuItem;
355 private MenuItem ultraPrivacyMenuItem;
356 private MenuItem blockAllThirdParyRequestsMenuItem;
358 // The blocklist variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
359 private boolean easyListEnabled;
360 private boolean easyPrivacyEnabled;
361 private boolean fanboysAnnoyanceListEnabled;
362 private boolean fanboysSocialBlockingListEnabled;
363 private boolean ultraPrivacyEnabled;
365 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
366 private String webViewDefaultUserAgent;
368 // `defaultCustomUserAgentString` is used in `onPrepareOptionsMenu()` and `applyDomainSettings()`.
369 private String defaultCustomUserAgentString;
371 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
372 private Runtime privacyBrowserRuntime;
374 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
375 private boolean proxyThroughOrbot;
377 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
378 private boolean incognitoModeEnabled;
380 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
381 private boolean fullScreenBrowsingModeEnabled;
383 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
384 private boolean inFullScreenBrowsingMode;
386 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
387 private boolean hideSystemBarsOnFullscreen;
389 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
390 private boolean translucentNavigationBarOnFullscreen;
392 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
393 private boolean reapplyDomainSettingsOnRestart;
395 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
396 private boolean reapplyAppSettingsOnRestart;
398 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
399 private boolean displayingFullScreenVideo;
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 // `orbotStatusBroadcastReciever` is used in `onCreate()` and `onDestroy()`.
408 private BroadcastReceiver orbotStatusBroadcastReceiver;
410 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyAppSettings()`.
411 private boolean waitingForOrbot;
413 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
414 private boolean domainSettingsApplied;
416 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
417 private int displayWebpageImagesInt;
419 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
420 private boolean onTheFlyDisplayImagesSet;
422 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
423 private String waitingForOrbotHTMLString;
425 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
426 private String privateDataDirectoryString;
428 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
429 private LinearLayout findOnPageLinearLayout;
431 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
432 private EditText findOnPageEditText;
434 // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
435 private boolean displayAdditionalAppBarIcons;
437 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
438 private ActionBarDrawerToggle drawerToggle;
440 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
441 private Toolbar supportAppBar;
443 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
444 private EditText urlTextBox;
446 // The color spans are used in `onCreate()` and `highlightUrlText()`.
447 private ForegroundColorSpan redColorSpan;
448 private ForegroundColorSpan initialGrayColorSpan;
449 private ForegroundColorSpan finalGrayColorSpan;
451 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
452 private SslErrorHandler sslErrorHandler;
454 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
455 private static HttpAuthHandler httpAuthHandler;
457 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
458 private InputMethodManager inputMethodManager;
460 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
461 private RelativeLayout mainWebViewRelativeLayout;
463 // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
464 private boolean urlIsLoading;
466 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
467 private boolean pinnedDomainSslCertificate;
469 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
470 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
472 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
473 private ListView bookmarksListView;
475 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
476 private TextView bookmarksTitleTextView;
478 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
479 private Cursor bookmarksCursor;
481 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
482 private CursorAdapter bookmarksCursorAdapter;
484 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
485 private String oldFolderNameString;
487 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
488 private ValueCallback<Uri[]> fileChooserCallback;
490 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
491 private String downloadUrl;
492 private String downloadContentDisposition;
493 private long downloadContentLength;
495 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
496 private String downloadImageUrl;
498 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
499 private ArrayAdapter<CharSequence> userAgentNamesArray;
500 private String[] userAgentDataArray;
502 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
503 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
504 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
507 // 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.
508 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
509 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
510 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
511 @SuppressWarnings("deprecation")
512 protected void onCreate(Bundle savedInstanceState) {
513 // Get a handle for the shared preferences.
514 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
516 // Get the theme and screenshot preferences.
517 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
518 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
520 // Disable screenshots if not allowed.
521 if (!allowScreenshots) {
522 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
525 // Set the activity theme.
527 setTheme(R.style.PrivacyBrowserDark);
529 setTheme(R.style.PrivacyBrowserLight);
532 // Run the default commands.
533 super.onCreate(savedInstanceState);
535 // Set the content view.
536 setContentView(R.layout.main_drawerlayout);
538 // Get a handle for `inputMethodManager`.
539 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
541 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
542 supportAppBar = findViewById(R.id.app_bar);
543 setSupportActionBar(supportAppBar);
544 appBar = getSupportActionBar();
546 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
547 assert appBar != null;
549 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
550 appBar.setCustomView(R.layout.url_app_bar);
551 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
553 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
554 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
555 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
556 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
558 // Get a handle for `urlTextBox`.
559 urlTextBox = findViewById(R.id.url_edittext);
561 // Remove the formatting from `urlTextBar` when the user is editing the text.
562 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
563 if (hasFocus) { // The user is editing `urlTextBox`.
564 // Remove the highlighting.
565 urlTextBox.getText().removeSpan(redColorSpan);
566 urlTextBox.getText().removeSpan(initialGrayColorSpan);
567 urlTextBox.getText().removeSpan(finalGrayColorSpan);
568 } else { // The user has stopped editing `urlTextBox`.
569 // Reapply the highlighting.
574 // Set the go button on the keyboard to load the URL in `urlTextBox`.
575 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
576 // If the event is a key-down event on the `enter` button, load the URL.
577 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
578 // Load the URL into the mainWebView and consume the event.
580 loadUrlFromTextBox();
581 } catch (UnsupportedEncodingException e) {
584 // If the enter key was pressed, consume the event.
587 // If any other key was pressed, do not consume the event.
592 // Set `waitingForOrbotHTMLString`.
593 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
595 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
596 currentDomainName = "";
597 orbotStatus = "unknown";
598 waitingForOrbot = false;
600 // Create an Orbot status `BroadcastReceiver`.
601 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
603 public void onReceive(Context context, Intent intent) {
604 // Store the content of the status message in `orbotStatus`.
605 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
607 // If we are waiting on Orbot, load the website now that Orbot is connected.
608 if (orbotStatus.equals("ON") && waitingForOrbot) {
609 // Reset `waitingForOrbot`.
610 waitingForOrbot = false;
612 // Load `formattedUrlString
613 loadUrl(formattedUrlString);
618 // Register `orbotStatusBroadcastReceiver` on `this` context.
619 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
621 // Get handles for views that need to be accessed.
622 drawerLayout = findViewById(R.id.drawerlayout);
623 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
624 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
625 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
626 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
627 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
628 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
629 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
630 mainWebView = findViewById(R.id.main_webview);
631 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
632 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
633 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
634 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
635 favoriteIconImageView = findViewById(R.id.favorite_icon);
637 // 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.
639 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
640 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
641 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
642 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
644 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
645 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
646 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
647 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
650 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
651 launchBookmarksActivityFab.setOnClickListener(v -> {
652 // Create an intent to launch the bookmarks activity.
653 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
655 // Include the current folder with the `Intent`.
656 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
659 startActivity(bookmarksIntent);
662 // Set the create new bookmark folder FAB to display an alert dialog.
663 createBookmarkFolderFab.setOnClickListener(v -> {
664 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
665 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
666 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
669 // Set the create new bookmark FAB to display an alert dialog.
670 createBookmarkFab.setOnClickListener(view -> {
671 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
672 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
673 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
676 // Create a double-tap listener to toggle full-screen mode.
677 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
678 // Override `onDoubleTap()`. All other events are handled using the default settings.
680 public boolean onDoubleTap(MotionEvent event) {
681 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
682 // Toggle `inFullScreenBrowsingMode`.
683 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
685 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
686 // Hide the `appBar`.
689 // Hide the banner ad in the free flavor.
690 if (BuildConfig.FLAVOR.contentEquals("free")) {
691 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
692 AdHelper.hideAd(findViewById(R.id.adview));
695 // Modify the system bars.
696 if (hideSystemBarsOnFullscreen) { // Hide everything.
697 // Remove the translucent overlays.
698 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
700 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
701 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
703 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
704 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
705 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
707 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
709 // Set `rootCoordinatorLayout` to fill the whole screen.
710 rootCoordinatorLayout.setFitsSystemWindows(false);
711 } else { // Hide everything except the status and navigation bars.
712 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
713 rootCoordinatorLayout.setFitsSystemWindows(false);
715 // 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.
716 if (translucentNavigationBarOnFullscreen) {
717 // Set the navigation bar to be translucent.
718 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
721 } else { // Switch to normal viewing mode.
722 // Show the `appBar`.
725 // Show the `BannerAd` in the free flavor.
726 if (BuildConfig.FLAVOR.contentEquals("free")) {
727 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
728 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
731 // Remove the translucent navigation bar flag if it is set.
732 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
734 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
735 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
737 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
738 rootCoordinatorLayout.setSystemUiVisibility(0);
740 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
741 rootCoordinatorLayout.setFitsSystemWindows(true);
744 // Consume the double-tap.
746 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
752 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
753 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
754 // Call `performClick()` on the view, which is required for accessibility.
757 // Send the `event` to `gestureDetector`.
758 return gestureDetector.onTouchEvent(event);
761 // Update `findOnPageCountTextView`.
762 mainWebView.setFindListener(new WebView.FindListener() {
763 // Get a handle for `findOnPageCountTextView`.
764 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
767 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
768 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
769 // Set `findOnPageCountTextView` to `0/0`.
770 findOnPageCountTextView.setText(R.string.zero_of_zero);
771 } else if (isDoneCounting) { // There are matches.
772 // `activeMatchOrdinal` is zero-based.
773 int activeMatch = activeMatchOrdinal + 1;
775 // Build the match string.
776 String matchString = activeMatch + "/" + numberOfMatches;
778 // Set `findOnPageCountTextView`.
779 findOnPageCountTextView.setText(matchString);
784 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
785 findOnPageEditText.addTextChangedListener(new TextWatcher() {
787 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
792 public void onTextChanged(CharSequence s, int start, int before, int count) {
797 public void afterTextChanged(Editable s) {
798 // Search for the text in `mainWebView`.
799 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
803 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
804 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
805 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
806 // Hide the soft keyboard. `0` indicates no additional flags.
807 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
809 // Consume the event.
811 } else { // A different key was pressed.
812 // Do not consume the event.
817 // Implement swipe to refresh
818 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
819 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
820 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
822 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
823 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
824 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
826 // Listen for touches on the navigation menu.
827 final NavigationView navigationView = findViewById(R.id.navigationview);
828 navigationView.setNavigationItemSelectedListener(this);
830 // 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.
831 final Menu navigationMenu = navigationView.getMenu();
832 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
833 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
834 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
835 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
837 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
838 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
839 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
841 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
842 currentBookmarksFolder = "";
844 // Load the home folder, which is `""` in the database.
845 loadBookmarksFolder();
847 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
848 // Convert the id from long to int to match the format of the bookmarks database.
849 int databaseID = (int) id;
851 // Get the bookmark cursor for this ID and move it to the first row.
852 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
853 bookmarkCursor.moveToFirst();
855 // Act upon the bookmark according to the type.
856 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
857 // Store the new folder name in `currentBookmarksFolder`.
858 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
860 // Load the new folder.
861 loadBookmarksFolder();
862 } else { // The selected bookmark is not a folder.
863 // Load the bookmark URL.
864 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
866 // Close the bookmarks drawer.
867 drawerLayout.closeDrawer(GravityCompat.END);
870 // Close the `Cursor`.
871 bookmarkCursor.close();
874 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
875 // Convert the database ID from `long` to `int`.
876 int databaseId = (int) id;
878 // Find out if the selected bookmark is a folder.
879 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
882 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
883 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
885 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
886 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
887 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
889 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
890 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
891 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
894 // Consume the event.
898 // The drawer listener is used to update the navigation menu.
899 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
901 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
905 public void onDrawerOpened(@NonNull View drawerView) {
909 public void onDrawerClosed(@NonNull View drawerView) {
913 public void onDrawerStateChanged(int newState) {
914 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
915 // Update the back, forward, history, and requests menu items.
916 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
917 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
918 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
919 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
921 // Hide the keyboard (if displayed).
922 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
924 // Clear the focus from from the URL text box.
925 urlTextBox.clearFocus();
930 // drawerToggle creates the hamburger icon at the start of the AppBar.
931 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
933 // Get a handle for the progress bar.
934 final ProgressBar progressBar = findViewById(R.id.progress_bar);
936 mainWebView.setWebChromeClient(new WebChromeClient() {
937 // Update the progress bar when a page is loading.
939 public void onProgressChanged(WebView view, int progress) {
940 // Inject the night mode CSS if night mode is enabled.
942 // `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
943 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
944 // `border: none` removes all borders, which can also be used to underline text.
945 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
946 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
947 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
948 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
949 // Initialize a `Handler` to display `mainWebView`.
950 Handler displayWebViewHandler = new Handler();
952 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
953 Runnable displayWebViewRunnable = () -> {
954 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
955 if (progressBar.getVisibility() == View.GONE) {
956 mainWebView.setVisibility(View.VISIBLE);
960 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
961 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
965 // Update the progress bar.
966 progressBar.setProgress(progress);
968 // Set the visibility of the progress bar.
969 if (progress < 100) {
970 // Show the progress bar.
971 progressBar.setVisibility(View.VISIBLE);
973 // Hide the progress bar.
974 progressBar.setVisibility(View.GONE);
976 // Display `mainWebView` if night mode is disabled.
977 // 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
978 // currently enabled.
980 mainWebView.setVisibility(View.VISIBLE);
983 //Stop the swipe to refresh indicator if it is running
984 swipeRefreshLayout.setRefreshing(false);
988 // Set the favorite icon when it changes.
990 public void onReceivedIcon(WebView view, Bitmap icon) {
991 // Only update the favorite icon if the website has finished loading.
992 if (progressBar.getVisibility() == View.GONE) {
993 // Save a copy of the favorite icon.
994 favoriteIconBitmap = icon;
996 // Place the favorite icon in the appBar.
997 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1001 // Save a copy of the title when it changes.
1003 public void onReceivedTitle(WebView view, String title) {
1004 // Save a copy of the title.
1005 webViewTitle = title;
1008 // Enter full screen video.
1010 public void onShowCustomView(View view, CustomViewCallback callback) {
1011 // Set the full screen video flag.
1012 displayingFullScreenVideo = true;
1014 // Pause the ad if this is the free flavor.
1015 if (BuildConfig.FLAVOR.contentEquals("free")) {
1016 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1017 AdHelper.pauseAd(findViewById(R.id.adview));
1020 // Remove the translucent overlays.
1021 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1023 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1024 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1026 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1027 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1028 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1030 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1032 // Set `rootCoordinatorLayout` to fill the entire screen.
1033 rootCoordinatorLayout.setFitsSystemWindows(false);
1035 // Disable the sliding drawers.
1036 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1038 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1039 fullScreenVideoFrameLayout.addView(view);
1040 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1043 // Exit full screen video.
1045 public void onHideCustomView() {
1046 // Unset the full screen video flag.
1047 displayingFullScreenVideo = false;
1049 // Hide `fullScreenVideoFrameLayout`.
1050 fullScreenVideoFrameLayout.removeAllViews();
1051 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1053 // Enable the sliding drawers.
1054 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1056 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1057 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1058 if (hideSystemBarsOnFullscreen) { // Hide everything.
1059 // Remove the translucent navigation setting if it is currently flagged.
1060 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1062 // Remove the translucent status bar overlay.
1063 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1065 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1066 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1068 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1069 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1070 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1072 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1073 } else { // Hide everything except the status and navigation bars.
1074 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1075 rootCoordinatorLayout.setSystemUiVisibility(0);
1077 // Add the translucent status flag if it is unset.
1078 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1080 if (translucentNavigationBarOnFullscreen) {
1081 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1082 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1084 // Set the navigation bar to be black.
1085 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1088 } else { // Switch to normal viewing mode.
1089 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1090 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1094 // Show the `BannerAd` in the free flavor.
1095 if (BuildConfig.FLAVOR.contentEquals("free")) {
1096 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1097 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1100 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1101 rootCoordinatorLayout.setSystemUiVisibility(0);
1103 // Remove the translucent navigation bar flag if it is set.
1104 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1106 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1107 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1109 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1110 rootCoordinatorLayout.setFitsSystemWindows(true);
1113 // Show the ad if this is the free flavor.
1114 if (BuildConfig.FLAVOR.contentEquals("free")) {
1115 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1116 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1122 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1123 // Show the file chooser if the device is running API >= 21.
1124 if (Build.VERSION.SDK_INT >= 21) {
1125 // Store the file path callback.
1126 fileChooserCallback = filePathCallback;
1128 // Create an intent to open a chooser based ont the file chooser parameters.
1129 Intent fileChooserIntent = fileChooserParams.createIntent();
1131 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1132 startActivityForResult(fileChooserIntent, 0);
1138 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1139 registerForContextMenu(mainWebView);
1141 // Allow the downloading of files.
1142 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1143 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1144 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1145 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1147 // Store the variables for future use by `onRequestPermissionsResult()`.
1149 downloadContentDisposition = contentDisposition;
1150 downloadContentLength = contentLength;
1152 // Show a dialog if the user has previously denied the permission.
1153 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1154 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1155 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1157 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1158 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1159 } else { // Show the permission request directly.
1160 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1161 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1163 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1164 // Get a handle for the download file alert dialog.
1165 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1167 // Show the download file alert dialog.
1168 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1172 // Allow pinch to zoom.
1173 mainWebView.getSettings().setBuiltInZoomControls(true);
1175 // Hide zoom controls.
1176 mainWebView.getSettings().setDisplayZoomControls(false);
1178 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1179 mainWebView.getSettings().setUseWideViewPort(true);
1181 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1182 mainWebView.getSettings().setLoadWithOverviewMode(true);
1184 // Explicitly disable geolocation.
1185 mainWebView.getSettings().setGeolocationEnabled(false);
1187 // Initialize cookieManager.
1188 cookieManager = CookieManager.getInstance();
1190 // 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).
1191 customHeaders.put("X-Requested-With", "");
1193 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1194 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1196 // Get the intent that started the app.
1197 final Intent launchingIntent = getIntent();
1199 // Extract the launching intent data as `launchingIntentUriData`.
1200 final Uri launchingIntentUriData = launchingIntent.getData();
1202 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1203 if (launchingIntentUriData != null) {
1204 formattedUrlString = launchingIntentUriData.toString();
1207 // Get a handle for the `Runtime`.
1208 privacyBrowserRuntime = Runtime.getRuntime();
1210 // Store the application's private data directory.
1211 privateDataDirectoryString = getApplicationInfo().dataDir;
1212 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1214 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1215 inFullScreenBrowsingMode = false;
1217 // Initialize the privacy settings variables.
1218 javaScriptEnabled = false;
1219 firstPartyCookiesEnabled = false;
1220 thirdPartyCookiesEnabled = false;
1221 domStorageEnabled = false;
1222 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1225 // Store the default user agent.
1226 webViewDefaultUserAgent = mainWebView.getSettings().getUserAgentString();
1228 // Initialize the WebView title.
1229 webViewTitle = getString(R.string.no_title);
1231 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1232 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1233 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1234 assert favoriteIconBitmapDrawable != null;
1235 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1237 // If the favorite icon is null, load the default.
1238 if (favoriteIconBitmap == null) {
1239 favoriteIconBitmap = favoriteIconDefaultBitmap;
1242 // Initialize the user agent array adapter and string array.
1243 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1244 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1246 // Apply the app settings from the shared preferences.
1249 // Instantiate the block list helper.
1250 BlockListHelper blockListHelper = new BlockListHelper();
1252 // Initialize the list of resource requests.
1253 resourceRequests = new ArrayList<>();
1255 // Parse the block lists.
1256 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1257 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1258 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1259 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1260 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1262 // Store the list versions.
1263 easyListVersion = easyList.get(0).get(0)[0];
1264 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1265 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1266 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1267 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1269 // Get a handle for the activity. This is used to update the requests counter while the navigation menu is open.
1270 Activity activity = this;
1272 mainWebView.setWebViewClient(new WebViewClient() {
1273 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1274 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1275 @SuppressWarnings("deprecation")
1277 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1278 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1279 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1280 formattedUrlString = "";
1282 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1283 applyDomainSettings(url, true, false);
1285 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1287 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1288 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1289 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1291 // Parse the url and set it as the data for the intent.
1292 emailIntent.setData(Uri.parse(url));
1294 // Open the email program in a new task instead of as part of Privacy Browser.
1295 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1298 startActivity(emailIntent);
1300 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1302 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1303 // Open the dialer and load the phone number, but wait for the user to place the call.
1304 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1306 // Add the phone number to the intent.
1307 dialIntent.setData(Uri.parse(url));
1309 // Open the dialer in a new task instead of as part of Privacy Browser.
1310 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1313 startActivity(dialIntent);
1315 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1317 } else { // Load a system chooser to select an app that can handle the URL.
1318 // Open an app that can handle the URL.
1319 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1321 // Add the URL to the intent.
1322 genericIntent.setData(Uri.parse(url));
1324 // List all apps that can handle the URL instead of just opening the first one.
1325 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1327 // Open the app in a new task instead of as part of Privacy Browser.
1328 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1330 // Start the app or display a snackbar if no app is available to handle the URL.
1332 startActivity(genericIntent);
1333 } catch (ActivityNotFoundException exception) {
1334 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1337 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1342 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1343 @SuppressWarnings("deprecation")
1345 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1346 // Create an empty web resource response to be used if the resource request is blocked.
1347 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1349 // Reset the whitelist results tracker.
1350 whiteListResultStringArray = null;
1352 // Initialize the third party request tracker.
1353 boolean isThirdPartyRequest = false;
1355 // Initialize the current domain string.
1356 String currentDomain = "";
1358 // Nobody is happy when comparing null strings.
1359 if (!(formattedUrlString == null) && !(url == null)) {
1360 // Get the domain strings to URIs.
1361 Uri currentDomainUri = Uri.parse(formattedUrlString);
1362 Uri requestDomainUri = Uri.parse(url);
1364 // Get the domain host names.
1365 String currentBaseDomain = currentDomainUri.getHost();
1366 String requestBaseDomain = requestDomainUri.getHost();
1368 // Update the current domain variable.
1369 currentDomain = currentBaseDomain;
1371 // Only compare the current base domain and the request base domain if neither is null.
1372 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1373 // Determine the current base domain.
1374 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1375 // Remove the first subdomain.
1376 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1379 // Determine the request base domain.
1380 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1381 // Remove the first subdomain.
1382 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1385 // Update the third party request tracker.
1386 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1390 // Block third-party requests if enabled.
1391 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1392 // Increment the blocked requests counters.
1394 thirdPartyBlockedRequests++;
1396 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1397 activity.runOnUiThread(() -> {
1398 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1399 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1400 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1403 // Add the request to the log.
1404 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1406 // Return an empty web resource response.
1407 return emptyWebResourceResponse;
1410 // Check UltraPrivacy if it is enabled.
1411 if (ultraPrivacyEnabled) {
1412 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1413 // Increment the blocked requests counters.
1415 ultraPrivacyBlockedRequests++;
1417 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1418 activity.runOnUiThread(() -> {
1419 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1420 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1421 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1424 // The resource request was blocked. Return an empty web resource response.
1425 return emptyWebResourceResponse;
1428 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1429 if (whiteListResultStringArray != null) {
1430 // Add a whitelist entry to the resource requests array.
1431 resourceRequests.add(whiteListResultStringArray);
1433 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1438 // Check EasyList if it is enabled.
1439 if (easyListEnabled) {
1440 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1441 // Increment the blocked requests counters.
1443 easyListBlockedRequests++;
1445 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1446 activity.runOnUiThread(() -> {
1447 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1448 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1449 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1452 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1453 whiteListResultStringArray = null;
1455 // The resource request was blocked. Return an empty web resource response.
1456 return emptyWebResourceResponse;
1460 // Check EasyPrivacy if it is enabled.
1461 if (easyPrivacyEnabled) {
1462 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1463 // Increment the blocked requests counters.
1465 easyPrivacyBlockedRequests++;
1467 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1468 activity.runOnUiThread(() -> {
1469 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1470 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1471 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1474 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1475 whiteListResultStringArray = null;
1477 // The resource request was blocked. Return an empty web resource response.
1478 return emptyWebResourceResponse;
1482 // Check Fanboy’s Annoyance List if it is enabled.
1483 if (fanboysAnnoyanceListEnabled) {
1484 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1485 // Increment the blocked requests counters.
1487 fanboysAnnoyanceListBlockedRequests++;
1489 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1490 activity.runOnUiThread(() -> {
1491 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1492 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1493 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1496 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1497 whiteListResultStringArray = null;
1499 // The resource request was blocked. Return an empty web resource response.
1500 return emptyWebResourceResponse;
1502 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1503 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1504 // Increment the blocked requests counters.
1506 fanboysSocialBlockingListBlockedRequests++;
1508 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1509 activity.runOnUiThread(() -> {
1510 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1511 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1512 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1515 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1516 whiteListResultStringArray = null;
1518 // The resource request was blocked. Return an empty web resource response.
1519 return emptyWebResourceResponse;
1523 // Add the request to the log because it hasn't been processed by any of the previous checks.
1524 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1525 resourceRequests.add(whiteListResultStringArray);
1526 } else { // The request didn't match any blocklist entry. Log it as a defult request.
1527 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1530 // The resource request has not been blocked. `return null` loads the requested resource.
1534 // Handle HTTP authentication requests.
1536 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1537 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1538 httpAuthHandler = handler;
1540 // Display the HTTP authentication dialog.
1541 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1542 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1545 // Update the URL in urlTextBox when the page starts to load.
1547 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1548 // Reset the list of resource requests.
1549 resourceRequests.clear();
1551 // Initialize the counters for requests blocked by each blocklist.
1552 blockedRequests = 0;
1553 easyListBlockedRequests = 0;
1554 easyPrivacyBlockedRequests = 0;
1555 fanboysAnnoyanceListBlockedRequests = 0;
1556 fanboysSocialBlockingListBlockedRequests = 0;
1557 ultraPrivacyBlockedRequests = 0;
1558 thirdPartyBlockedRequests = 0;
1560 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1562 mainWebView.setVisibility(View.INVISIBLE);
1565 // Hide the keyboard. `0` indicates no additional flags.
1566 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1568 // Check to see if Privacy Browser is waiting on Orbot.
1569 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1570 // 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.
1571 formattedUrlString = url;
1573 // Display the formatted URL text.
1574 urlTextBox.setText(formattedUrlString);
1576 // Apply text highlighting to `urlTextBox`.
1579 // Apply any custom domain settings if the URL was loaded by navigating history.
1580 if (navigatingHistory) {
1581 // Reset `navigatingHistory`.
1582 navigatingHistory = false;
1584 // Apply the domain settings.
1585 applyDomainSettings(url, true, false);
1588 // 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.
1589 urlIsLoading = true;
1591 // Replace Refresh with Stop if the menu item has been created. (The WebView typically begins loading before the menu items are instantiated.)
1592 if (refreshMenuItem != null) {
1594 refreshMenuItem.setTitle(R.string.stop);
1596 // If the icon is displayed in the AppBar, set it according to the theme.
1597 if (displayAdditionalAppBarIcons) {
1599 refreshMenuItem.setIcon(R.drawable.close_dark);
1601 refreshMenuItem.setIcon(R.drawable.close_light);
1608 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1610 public void onPageFinished(WebView view, String url) {
1611 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1612 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1613 cookieManager.flush();
1616 // Update the Refresh menu item if it has been created.
1617 if (refreshMenuItem != null) {
1618 // Reset the Refresh title.
1619 refreshMenuItem.setTitle(R.string.refresh);
1621 // If the icon is displayed in the AppBar, reset it according to the theme.
1622 if (displayAdditionalAppBarIcons) {
1624 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1626 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1631 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1632 urlIsLoading = false;
1634 // Clear the cache and history if Incognito Mode is enabled.
1635 if (incognitoModeEnabled) {
1636 // Clear the cache. `true` includes disk files.
1637 mainWebView.clearCache(true);
1639 // Clear the back/forward history.
1640 mainWebView.clearHistory();
1642 // Manually delete cache folders.
1644 // Delete the main cache directory.
1645 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1647 // Delete the secondary `Service Worker` cache directory.
1648 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1649 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1650 } catch (IOException e) {
1651 // Do nothing if an error is thrown.
1655 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1656 if (!waitingForOrbot) {
1657 // Check to see if `WebView` has set `url` to be `about:blank`.
1658 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1659 // Set `formattedUrlString` to `""`.
1660 formattedUrlString = "";
1662 urlTextBox.setText(formattedUrlString);
1664 // Request focus for `urlTextBox`.
1665 urlTextBox.requestFocus();
1667 // Display the keyboard.
1668 inputMethodManager.showSoftInput(urlTextBox, 0);
1670 // Apply the domain settings. This clears any settings from the previous domain.
1671 applyDomainSettings(formattedUrlString, true, false);
1672 } else { // `WebView` has loaded a webpage.
1673 // Set `formattedUrlString`.
1674 formattedUrlString = url;
1676 // Only update `urlTextBox` if the user is not typing in it.
1677 if (!urlTextBox.hasFocus()) {
1678 // Display the formatted URL text.
1679 urlTextBox.setText(formattedUrlString);
1681 // Apply text highlighting to `urlTextBox`.
1686 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1687 sslCertificate = mainWebView.getCertificate();
1689 // 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.
1690 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1691 // Initialize the current SSL certificate variables.
1692 String currentWebsiteIssuedToCName = "";
1693 String currentWebsiteIssuedToOName = "";
1694 String currentWebsiteIssuedToUName = "";
1695 String currentWebsiteIssuedByCName = "";
1696 String currentWebsiteIssuedByOName = "";
1697 String currentWebsiteIssuedByUName = "";
1698 Date currentWebsiteSslStartDate = null;
1699 Date currentWebsiteSslEndDate = null;
1702 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1703 if (sslCertificate != null) {
1704 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1705 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1706 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1707 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1708 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1709 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1710 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1711 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1714 // 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`.
1715 String currentWebsiteSslStartDateString = "";
1716 String currentWebsiteSslEndDateString = "";
1717 String pinnedDomainSslStartDateString = "";
1718 String pinnedDomainSslEndDateString = "";
1720 // Convert the `Dates` to `Strings` if they are not `null`.
1721 if (currentWebsiteSslStartDate != null) {
1722 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1725 if (currentWebsiteSslEndDate != null) {
1726 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1729 if (pinnedDomainSslStartDate != null) {
1730 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1733 if (pinnedDomainSslEndDate != null) {
1734 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1737 // Check to see if the pinned SSL certificate matches the current website certificate.
1738 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1739 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1740 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1741 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1742 // The pinned SSL certificate doesn't match the current domain certificate.
1743 //Display the pinned SSL certificate mismatch `AlertDialog`.
1744 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1745 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1751 // Handle SSL Certificate errors.
1753 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1754 // Get the current website SSL certificate.
1755 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1757 // Extract the individual pieces of information from the current website SSL certificate.
1758 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1759 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1760 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1761 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1762 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1763 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1764 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1765 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1767 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1768 if (pinnedDomainSslCertificate &&
1769 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1770 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1771 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1772 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1773 // An SSL certificate is pinned and matches the current domain certificate.
1774 // Proceed to the website without displaying an error.
1776 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1777 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1778 sslErrorHandler = handler;
1780 // Display the SSL error `AlertDialog`.
1781 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1782 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1787 // Load the website if not waiting for Orbot to connect.
1788 if (!waitingForOrbot) {
1789 loadUrl(formattedUrlString);
1794 protected void onNewIntent(Intent intent) {
1795 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1798 // Check to see if the intent contains a new URL.
1799 if (intent.getData() != null) {
1800 // Get the intent data.
1801 final Uri intentUriData = intent.getData();
1803 // Load the website.
1804 loadUrl(intentUriData.toString());
1806 // Close the navigation drawer if it is open.
1807 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1808 drawerLayout.closeDrawer(GravityCompat.START);
1811 // Close the bookmarks drawer if it is open.
1812 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1813 drawerLayout.closeDrawer(GravityCompat.END);
1816 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1817 mainWebView.requestFocus();
1822 public void onRestart() {
1823 // Run the default commands.
1826 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1827 if (proxyThroughOrbot) {
1828 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1829 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1831 // Send the intent to the Orbot package.
1832 orbotIntent.setPackage("org.torproject.android");
1835 sendBroadcast(orbotIntent);
1838 // Apply the app settings if returning from the Settings activity..
1839 if (reapplyAppSettingsOnRestart) {
1840 // Apply the app settings.
1843 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1844 if (reloadOnRestart) {
1845 // Reload `mainWebView`.
1846 mainWebView.reload();
1848 // Reset `reloadOnRestartBoolean`.
1849 reloadOnRestart = false;
1852 // Reset the return from settings flag.
1853 reapplyAppSettingsOnRestart = false;
1856 // Apply the domain settings if returning from the Domains activity.
1857 if (reapplyDomainSettingsOnRestart) {
1858 // Reapply the domain settings.
1859 applyDomainSettings(formattedUrlString, false, true);
1861 // Reset `reapplyDomainSettingsOnRestart`.
1862 reapplyDomainSettingsOnRestart = false;
1865 // Load the URL on restart to apply changes to night mode.
1866 if (loadUrlOnRestart) {
1867 // Load the current `formattedUrlString`.
1868 loadUrl(formattedUrlString);
1870 // Reset `loadUrlOnRestart.
1871 loadUrlOnRestart = false;
1874 // Update the bookmarks drawer if returning from the Bookmarks activity.
1875 if (restartFromBookmarksActivity) {
1876 // Close the bookmarks drawer.
1877 drawerLayout.closeDrawer(GravityCompat.END);
1879 // Reload the bookmarks drawer.
1880 loadBookmarksFolder();
1882 // Reset `restartFromBookmarksActivity`.
1883 restartFromBookmarksActivity = false;
1886 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1887 updatePrivacyIcons(true);
1890 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1892 public void onResume() {
1893 // Run the default commands.
1896 // Resume JavaScript (if enabled).
1897 mainWebView.resumeTimers();
1899 // Resume `mainWebView`.
1900 mainWebView.onResume();
1902 // Resume the adView for the free flavor.
1903 if (BuildConfig.FLAVOR.contentEquals("free")) {
1905 AdHelper.resumeAd(findViewById(R.id.adview));
1908 // Display a message to the user if waiting for Orbot.
1909 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1910 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1911 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1914 if (displayingFullScreenVideo) {
1915 // Remove the translucent overlays.
1916 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1918 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1919 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1921 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1922 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1923 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1925 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1930 public void onPause() {
1931 // Run the default commands.
1934 // Pause `mainWebView`.
1935 mainWebView.onPause();
1937 // Stop all JavaScript.
1938 mainWebView.pauseTimers();
1940 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1941 if (BuildConfig.FLAVOR.contentEquals("free")) {
1943 AdHelper.pauseAd(findViewById(R.id.adview));
1948 public void onDestroy() {
1949 // Unregister the Orbot status broadcast receiver.
1950 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1952 // Run the default commands.
1957 public boolean onCreateOptionsMenu(Menu menu) {
1958 // Inflate the menu; this adds items to the action bar if it is present.
1959 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1961 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1964 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1965 updatePrivacyIcons(false);
1967 // Get handles for the menu items.
1968 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1969 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1970 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1971 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1972 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1973 refreshMenuItem = menu.findItem(R.id.refresh);
1974 blocklistsMenuItem = menu.findItem(R.id.blocklists);
1975 easyListMenuItem = menu.findItem(R.id.easylist);
1976 easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1977 fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1978 fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1979 ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1980 blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1981 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1983 // Only display third-party cookies if API >= 21
1984 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1986 // Only display the form data menu items if the API < 26.
1987 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1988 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1990 // Only show Ad Consent if this is the free flavor.
1991 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1993 // Get the shared preference values.
1994 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1996 // Get the status of the additional AppBar icons.
1997 displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1999 // 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.
2000 if (displayAdditionalAppBarIcons) {
2001 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2002 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2003 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
2004 } else { //Do not display the additional icons.
2005 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2006 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2007 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2010 // Replace Refresh with Stop if a URL is already loading.
2013 refreshMenuItem.setTitle(R.string.stop);
2015 // If the icon is displayed in the AppBar, set it according to the theme.
2016 if (displayAdditionalAppBarIcons) {
2018 refreshMenuItem.setIcon(R.drawable.close_dark);
2020 refreshMenuItem.setIcon(R.drawable.close_light);
2029 public boolean onPrepareOptionsMenu(Menu menu) {
2030 // Get handles for the menu items.
2031 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2032 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2033 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2034 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2035 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
2036 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2037 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2038 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2039 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
2040 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2041 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
2042 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2044 // Set the text for the domain menu item.
2045 if (domainSettingsApplied) {
2046 addOrEditDomain.setTitle(R.string.edit_domain_settings);
2048 addOrEditDomain.setTitle(R.string.add_domain_settings);
2051 // Set the status of the menu item checkboxes.
2052 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2053 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2054 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2055 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
2056 easyListMenuItem.setChecked(easyListEnabled);
2057 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
2058 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
2059 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
2060 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
2061 blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
2062 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
2063 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2065 // Enable third-party cookies if first-party cookies are enabled.
2066 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2068 // Enable DOM Storage if JavaScript is enabled.
2069 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2071 // Enable Clear Cookies if there are any.
2072 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2074 // Get a count of the number of files in the Local Storage directory.
2075 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2076 int localStorageDirectoryNumberOfFiles = 0;
2077 if (localStorageDirectory.exists()) {
2078 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2081 // Get a count of the number of files in the IndexedDB directory.
2082 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2083 int indexedDBDirectoryNumberOfFiles = 0;
2084 if (indexedDBDirectory.exists()) {
2085 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2088 // Enable Clear DOM Storage if there is any.
2089 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2091 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
2092 if (Build.VERSION.SDK_INT < 26) {
2093 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2094 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2096 // Disable clear form data because it is not supported on current version of Android.
2097 clearFormDataMenuItem.setEnabled(false);
2100 // Enable Clear Data if any of the submenu items are enabled.
2101 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2103 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2104 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2106 // Initialize the display names for the blocklists with the number of blocked requests.
2107 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
2108 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2109 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2110 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2111 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2112 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2113 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2115 // Get the current user agent.
2116 String currentUserAgent = mainWebView.getSettings().getUserAgentString();
2118 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
2119 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
2120 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
2121 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
2122 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
2123 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
2124 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
2125 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
2126 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
2127 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
2128 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
2129 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
2130 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
2131 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
2132 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
2133 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
2134 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
2135 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
2136 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
2137 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
2138 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
2139 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
2140 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
2141 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
2142 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
2143 } else { // Custom user agent.
2144 menu.findItem(R.id.user_agent_custom).setChecked(true);
2147 // Initialize font size variables.
2148 int fontSize = mainWebView.getSettings().getTextZoom();
2149 String fontSizeTitle;
2150 MenuItem selectedFontSizeMenuItem;
2152 // Prepare the font size title and current size menu item.
2155 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2156 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2160 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2161 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2165 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2166 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2170 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2171 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2175 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2176 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2180 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2181 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2185 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2186 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2190 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2191 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2195 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2196 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2200 // Set the font size title and select the current size menu item.
2201 fontSizeMenuItem.setTitle(fontSizeTitle);
2202 selectedFontSizeMenuItem.setChecked(true);
2204 // Run all the other default commands.
2205 super.onPrepareOptionsMenu(menu);
2207 // Display the menu.
2212 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2213 @SuppressLint("SetJavaScriptEnabled")
2214 // removeAllCookies is deprecated, but it is required for API < 21.
2215 @SuppressWarnings("deprecation")
2216 public boolean onOptionsItemSelected(MenuItem menuItem) {
2217 // Get the selected menu item ID.
2218 int menuItemId = menuItem.getItemId();
2220 // Set the commands that relate to the menu entries.
2221 switch (menuItemId) {
2222 case R.id.toggle_javascript:
2223 // Switch the status of javaScriptEnabled.
2224 javaScriptEnabled = !javaScriptEnabled;
2226 // Apply the new JavaScript status.
2227 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2229 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2230 updatePrivacyIcons(true);
2232 // Display a `Snackbar`.
2233 if (javaScriptEnabled) { // JavaScrip is enabled.
2234 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2235 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2236 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2237 } else { // Privacy mode.
2238 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2241 // Reload the WebView.
2242 mainWebView.reload();
2245 case R.id.add_or_edit_domain:
2246 if (domainSettingsApplied) { // Edit the current domain settings.
2247 // Reapply the domain settings on returning to `MainWebViewActivity`.
2248 reapplyDomainSettingsOnRestart = true;
2249 currentDomainName = "";
2251 // Create an intent to launch the domains activity.
2252 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2254 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2255 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2256 domainsIntent.putExtra("closeOnBack", true);
2259 startActivity(domainsIntent);
2260 } else { // Add a new domain.
2261 // Apply the new domain settings on returning to `MainWebViewActivity`.
2262 reapplyDomainSettingsOnRestart = true;
2263 currentDomainName = "";
2265 // Get the current domain
2266 Uri currentUri = Uri.parse(formattedUrlString);
2267 String currentDomain = currentUri.getHost();
2269 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2270 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2272 // Create the domain and store the database ID.
2273 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2275 // Create an intent to launch the domains activity.
2276 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2278 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2279 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2280 domainsIntent.putExtra("closeOnBack", true);
2283 startActivity(domainsIntent);
2287 case R.id.toggle_first_party_cookies:
2288 // Switch the status of firstPartyCookiesEnabled.
2289 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2291 // Update the menu checkbox.
2292 menuItem.setChecked(firstPartyCookiesEnabled);
2294 // Apply the new cookie status.
2295 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2297 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2298 updatePrivacyIcons(true);
2300 // Display a `Snackbar`.
2301 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2302 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2303 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2304 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2305 } else { // Privacy mode.
2306 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2309 // Reload the WebView.
2310 mainWebView.reload();
2313 case R.id.toggle_third_party_cookies:
2314 if (Build.VERSION.SDK_INT >= 21) {
2315 // Switch the status of thirdPartyCookiesEnabled.
2316 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2318 // Update the menu checkbox.
2319 menuItem.setChecked(thirdPartyCookiesEnabled);
2321 // Apply the new cookie status.
2322 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2324 // Display a `Snackbar`.
2325 if (thirdPartyCookiesEnabled) {
2326 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2328 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2331 // Reload the WebView.
2332 mainWebView.reload();
2333 } // Else do nothing because SDK < 21.
2336 case R.id.toggle_dom_storage:
2337 // Switch the status of domStorageEnabled.
2338 domStorageEnabled = !domStorageEnabled;
2340 // Update the menu checkbox.
2341 menuItem.setChecked(domStorageEnabled);
2343 // Apply the new DOM Storage status.
2344 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2346 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2347 updatePrivacyIcons(true);
2349 // Display a `Snackbar`.
2350 if (domStorageEnabled) {
2351 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2353 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2356 // Reload the WebView.
2357 mainWebView.reload();
2360 // Form data can be removed once the minimum API >= 26.
2361 case R.id.toggle_save_form_data:
2362 // Switch the status of saveFormDataEnabled.
2363 saveFormDataEnabled = !saveFormDataEnabled;
2365 // Update the menu checkbox.
2366 menuItem.setChecked(saveFormDataEnabled);
2368 // Apply the new form data status.
2369 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2371 // Display a `Snackbar`.
2372 if (saveFormDataEnabled) {
2373 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2375 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2378 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2379 updatePrivacyIcons(true);
2381 // Reload the WebView.
2382 mainWebView.reload();
2385 case R.id.clear_cookies:
2386 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2387 .setAction(R.string.undo, v -> {
2388 // Do nothing because everything will be handled by `onDismissed()` below.
2390 .addCallback(new Snackbar.Callback() {
2392 public void onDismissed(Snackbar snackbar, int event) {
2394 // The user pushed the `Undo` button.
2395 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2399 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2401 // `cookieManager.removeAllCookie()` varies by SDK.
2402 if (Build.VERSION.SDK_INT < 21) {
2403 cookieManager.removeAllCookie();
2405 // `null` indicates no callback.
2406 cookieManager.removeAllCookies(null);
2414 case R.id.clear_dom_storage:
2415 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2416 .setAction(R.string.undo, v -> {
2417 // Do nothing because everything will be handled by `onDismissed()` below.
2419 .addCallback(new Snackbar.Callback() {
2421 public void onDismissed(Snackbar snackbar, int event) {
2423 // The user pushed the `Undo` button.
2424 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2428 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2430 // Delete the DOM Storage.
2431 WebStorage webStorage = WebStorage.getInstance();
2432 webStorage.deleteAllData();
2434 // Manually delete the DOM storage files and directories.
2436 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2437 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2439 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2440 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2441 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2442 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2443 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2444 } catch (IOException e) {
2445 // Do nothing if an error is thrown.
2453 // Form data can be remove once the minimum API >= 26.
2454 case R.id.clear_form_data:
2455 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2456 .setAction(R.string.undo, v -> {
2457 // Do nothing because everything will be handled by `onDismissed()` below.
2459 .addCallback(new Snackbar.Callback() {
2461 public void onDismissed(Snackbar snackbar, int event) {
2463 // The user pushed the `Undo` button.
2464 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2468 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2470 // Delete the form data.
2471 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2472 mainWebViewDatabase.clearFormData();
2480 // Toggle the EasyList status.
2481 easyListEnabled = !easyListEnabled;
2483 // Update the menu checkbox.
2484 menuItem.setChecked(easyListEnabled);
2486 // Reload the main WebView.
2487 mainWebView.reload();
2490 case R.id.easyprivacy:
2491 // Toggle the EasyPrivacy status.
2492 easyPrivacyEnabled = !easyPrivacyEnabled;
2494 // Update the menu checkbox.
2495 menuItem.setChecked(easyPrivacyEnabled);
2497 // Reload the main WebView.
2498 mainWebView.reload();
2501 case R.id.fanboys_annoyance_list:
2502 // Toggle Fanboy's Annoyance List status.
2503 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2505 // Update the menu checkbox.
2506 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2508 // Update the staus of Fanboy's Social Blocking List.
2509 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2510 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2512 // Reload the main WebView.
2513 mainWebView.reload();
2516 case R.id.fanboys_social_blocking_list:
2517 // Toggle Fanboy's Social Blocking List status.
2518 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2520 // Update the menu checkbox.
2521 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2523 // Reload the main WebView.
2524 mainWebView.reload();
2527 case R.id.ultraprivacy:
2528 // Toggle the UltraPrivacy status.
2529 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2531 // Update the menu checkbox.
2532 menuItem.setChecked(ultraPrivacyEnabled);
2534 // Reload the main WebView.
2535 mainWebView.reload();
2538 case R.id.block_all_third_party_requests:
2539 //Toggle the third-party requests blocker status.
2540 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2542 // Update the menu checkbox.
2543 menuItem.setChecked(blockAllThirdPartyRequests);
2545 // Reload the main WebView.
2546 mainWebView.reload();
2549 case R.id.user_agent_privacy_browser:
2550 // Update the user agent.
2551 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
2553 // Reload the WebView.
2554 mainWebView.reload();
2557 case R.id.user_agent_webview_default:
2558 // Update the user agent.
2559 mainWebView.getSettings().setUserAgentString("");
2561 // Reload the WebView.
2562 mainWebView.reload();
2565 case R.id.user_agent_firefox_on_android:
2566 // Update the user agent.
2567 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
2569 // Reload the WebView.
2570 mainWebView.reload();
2573 case R.id.user_agent_chrome_on_android:
2574 // Update the user agent.
2575 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
2577 // Reload the WebView.
2578 mainWebView.reload();
2581 case R.id.user_agent_safari_on_ios:
2582 // Update the user agent.
2583 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
2585 // Reload the WebView.
2586 mainWebView.reload();
2589 case R.id.user_agent_firefox_on_linux:
2590 // Update the user agent.
2591 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
2593 // Reload the WebView.
2594 mainWebView.reload();