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 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
366 private Runtime privacyBrowserRuntime;
368 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
369 private boolean proxyThroughOrbot;
371 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
372 private boolean incognitoModeEnabled;
374 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
375 private boolean fullScreenBrowsingModeEnabled;
377 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
378 private boolean inFullScreenBrowsingMode;
380 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
381 private boolean hideSystemBarsOnFullscreen;
383 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
384 private boolean translucentNavigationBarOnFullscreen;
386 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
387 private boolean reapplyDomainSettingsOnRestart;
389 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
390 private boolean reapplyAppSettingsOnRestart;
392 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
393 private boolean displayingFullScreenVideo;
395 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
396 private String currentDomainName;
398 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
399 private boolean ignorePinnedSslCertificate;
401 // `orbotStatusBroadcastReciever` is used in `onCreate()` and `onDestroy()`.
402 private BroadcastReceiver orbotStatusBroadcastReceiver;
404 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyAppSettings()`.
405 private boolean waitingForOrbot;
407 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
408 private boolean domainSettingsApplied;
410 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
411 private int displayWebpageImagesInt;
413 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
414 private boolean onTheFlyDisplayImagesSet;
416 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
417 private String waitingForOrbotHTMLString;
419 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
420 private String privateDataDirectoryString;
422 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
423 private LinearLayout findOnPageLinearLayout;
425 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
426 private EditText findOnPageEditText;
428 // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
429 private boolean displayAdditionalAppBarIcons;
431 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
432 private ActionBarDrawerToggle drawerToggle;
434 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
435 private Toolbar supportAppBar;
437 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
438 private EditText urlTextBox;
440 // The color spans are used in `onCreate()` and `highlightUrlText()`.
441 private ForegroundColorSpan redColorSpan;
442 private ForegroundColorSpan initialGrayColorSpan;
443 private ForegroundColorSpan finalGrayColorSpan;
445 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
446 private SslErrorHandler sslErrorHandler;
448 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
449 private static HttpAuthHandler httpAuthHandler;
451 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
452 private InputMethodManager inputMethodManager;
454 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
455 private RelativeLayout mainWebViewRelativeLayout;
457 // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
458 private boolean urlIsLoading;
460 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
461 private boolean pinnedDomainSslCertificate;
463 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
464 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
466 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
467 private ListView bookmarksListView;
469 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
470 private TextView bookmarksTitleTextView;
472 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
473 private Cursor bookmarksCursor;
475 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
476 private CursorAdapter bookmarksCursorAdapter;
478 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
479 private String oldFolderNameString;
481 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
482 private ValueCallback<Uri[]> fileChooserCallback;
484 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
485 private String downloadUrl;
486 private String downloadContentDisposition;
487 private long downloadContentLength;
489 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
490 private String downloadImageUrl;
492 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
493 private ArrayAdapter<CharSequence> userAgentNamesArray;
494 private String[] userAgentDataArray;
496 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
497 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
498 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
501 // 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.
502 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
503 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
504 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
505 @SuppressWarnings("deprecation")
506 protected void onCreate(Bundle savedInstanceState) {
507 // Get a handle for the shared preferences.
508 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
510 // Get the theme and screenshot preferences.
511 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
512 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
514 // Disable screenshots if not allowed.
515 if (!allowScreenshots) {
516 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
519 // Set the activity theme.
521 setTheme(R.style.PrivacyBrowserDark);
523 setTheme(R.style.PrivacyBrowserLight);
526 // Run the default commands.
527 super.onCreate(savedInstanceState);
529 // Set the content view.
530 setContentView(R.layout.main_drawerlayout);
532 // Get a handle for `inputMethodManager`.
533 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
535 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
536 supportAppBar = findViewById(R.id.app_bar);
537 setSupportActionBar(supportAppBar);
538 appBar = getSupportActionBar();
540 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
541 assert appBar != null;
543 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
544 appBar.setCustomView(R.layout.url_app_bar);
545 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
547 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
548 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
549 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
550 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
552 // Get a handle for `urlTextBox`.
553 urlTextBox = findViewById(R.id.url_edittext);
555 // Remove the formatting from `urlTextBar` when the user is editing the text.
556 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
557 if (hasFocus) { // The user is editing `urlTextBox`.
558 // Remove the highlighting.
559 urlTextBox.getText().removeSpan(redColorSpan);
560 urlTextBox.getText().removeSpan(initialGrayColorSpan);
561 urlTextBox.getText().removeSpan(finalGrayColorSpan);
562 } else { // The user has stopped editing `urlTextBox`.
563 // Reapply the highlighting.
568 // Set the go button on the keyboard to load the URL in `urlTextBox`.
569 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
570 // If the event is a key-down event on the `enter` button, load the URL.
571 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
572 // Load the URL into the mainWebView and consume the event.
574 loadUrlFromTextBox();
575 } catch (UnsupportedEncodingException e) {
578 // If the enter key was pressed, consume the event.
581 // If any other key was pressed, do not consume the event.
586 // Set `waitingForOrbotHTMLString`.
587 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
589 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
590 currentDomainName = "";
591 orbotStatus = "unknown";
592 waitingForOrbot = false;
594 // Create an Orbot status `BroadcastReceiver`.
595 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
597 public void onReceive(Context context, Intent intent) {
598 // Store the content of the status message in `orbotStatus`.
599 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
601 // If we are waiting on Orbot, load the website now that Orbot is connected.
602 if (orbotStatus.equals("ON") && waitingForOrbot) {
603 // Reset `waitingForOrbot`.
604 waitingForOrbot = false;
606 // Load `formattedUrlString
607 loadUrl(formattedUrlString);
612 // Register `orbotStatusBroadcastReceiver` on `this` context.
613 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
615 // Get handles for views that need to be accessed.
616 drawerLayout = findViewById(R.id.drawerlayout);
617 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
618 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
619 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
620 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
621 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
622 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
623 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
624 mainWebView = findViewById(R.id.main_webview);
625 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
626 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
627 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
628 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
629 favoriteIconImageView = findViewById(R.id.favorite_icon);
631 // 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.
633 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
634 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
635 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
636 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
638 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
639 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
640 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
641 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
644 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
645 launchBookmarksActivityFab.setOnClickListener(v -> {
646 // Create an intent to launch the bookmarks activity.
647 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
649 // Include the current folder with the `Intent`.
650 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
653 startActivity(bookmarksIntent);
656 // Set the create new bookmark folder FAB to display an alert dialog.
657 createBookmarkFolderFab.setOnClickListener(v -> {
658 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
659 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
660 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
663 // Set the create new bookmark FAB to display an alert dialog.
664 createBookmarkFab.setOnClickListener(view -> {
665 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
666 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
667 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
670 // Create a double-tap listener to toggle full-screen mode.
671 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
672 // Override `onDoubleTap()`. All other events are handled using the default settings.
674 public boolean onDoubleTap(MotionEvent event) {
675 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
676 // Toggle `inFullScreenBrowsingMode`.
677 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
679 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
680 // Hide the `appBar`.
683 // Hide the banner ad in the free flavor.
684 if (BuildConfig.FLAVOR.contentEquals("free")) {
685 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
686 AdHelper.hideAd(findViewById(R.id.adview));
689 // Modify the system bars.
690 if (hideSystemBarsOnFullscreen) { // Hide everything.
691 // Remove the translucent overlays.
692 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
694 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
695 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
697 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
698 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
699 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
701 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
703 // Set `rootCoordinatorLayout` to fill the whole screen.
704 rootCoordinatorLayout.setFitsSystemWindows(false);
705 } else { // Hide everything except the status and navigation bars.
706 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
707 rootCoordinatorLayout.setFitsSystemWindows(false);
709 // 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.
710 if (translucentNavigationBarOnFullscreen) {
711 // Set the navigation bar to be translucent.
712 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
715 } else { // Switch to normal viewing mode.
716 // Show the `appBar`.
719 // Show the `BannerAd` in the free flavor.
720 if (BuildConfig.FLAVOR.contentEquals("free")) {
721 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
722 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
725 // Remove the translucent navigation bar flag if it is set.
726 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
728 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
729 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
731 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
732 rootCoordinatorLayout.setSystemUiVisibility(0);
734 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
735 rootCoordinatorLayout.setFitsSystemWindows(true);
738 // Consume the double-tap.
740 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
746 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
747 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
748 // Call `performClick()` on the view, which is required for accessibility.
751 // Send the `event` to `gestureDetector`.
752 return gestureDetector.onTouchEvent(event);
755 // Update `findOnPageCountTextView`.
756 mainWebView.setFindListener(new WebView.FindListener() {
757 // Get a handle for `findOnPageCountTextView`.
758 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
761 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
762 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
763 // Set `findOnPageCountTextView` to `0/0`.
764 findOnPageCountTextView.setText(R.string.zero_of_zero);
765 } else if (isDoneCounting) { // There are matches.
766 // `activeMatchOrdinal` is zero-based.
767 int activeMatch = activeMatchOrdinal + 1;
769 // Build the match string.
770 String matchString = activeMatch + "/" + numberOfMatches;
772 // Set `findOnPageCountTextView`.
773 findOnPageCountTextView.setText(matchString);
778 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
779 findOnPageEditText.addTextChangedListener(new TextWatcher() {
781 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
786 public void onTextChanged(CharSequence s, int start, int before, int count) {
791 public void afterTextChanged(Editable s) {
792 // Search for the text in `mainWebView`.
793 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
797 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
798 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
799 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
800 // Hide the soft keyboard. `0` indicates no additional flags.
801 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
803 // Consume the event.
805 } else { // A different key was pressed.
806 // Do not consume the event.
811 // Implement swipe to refresh
812 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
813 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
814 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
816 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
817 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
818 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
820 // Listen for touches on the navigation menu.
821 final NavigationView navigationView = findViewById(R.id.navigationview);
822 navigationView.setNavigationItemSelectedListener(this);
824 // 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.
825 final Menu navigationMenu = navigationView.getMenu();
826 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
827 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
828 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
829 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
831 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
832 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
833 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
835 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
836 currentBookmarksFolder = "";
838 // Load the home folder, which is `""` in the database.
839 loadBookmarksFolder();
841 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
842 // Convert the id from long to int to match the format of the bookmarks database.
843 int databaseID = (int) id;
845 // Get the bookmark cursor for this ID and move it to the first row.
846 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
847 bookmarkCursor.moveToFirst();
849 // Act upon the bookmark according to the type.
850 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
851 // Store the new folder name in `currentBookmarksFolder`.
852 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
854 // Load the new folder.
855 loadBookmarksFolder();
856 } else { // The selected bookmark is not a folder.
857 // Load the bookmark URL.
858 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
860 // Close the bookmarks drawer.
861 drawerLayout.closeDrawer(GravityCompat.END);
864 // Close the `Cursor`.
865 bookmarkCursor.close();
868 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
869 // Convert the database ID from `long` to `int`.
870 int databaseId = (int) id;
872 // Find out if the selected bookmark is a folder.
873 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
876 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
877 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
879 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
880 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
881 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
883 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
884 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
885 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
888 // Consume the event.
892 // The drawer listener is used to update the navigation menu.
893 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
895 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
899 public void onDrawerOpened(@NonNull View drawerView) {
903 public void onDrawerClosed(@NonNull View drawerView) {
907 public void onDrawerStateChanged(int newState) {
908 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
909 // Update the back, forward, history, and requests menu items.
910 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
911 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
912 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
913 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
915 // Hide the keyboard (if displayed).
916 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
918 // Clear the focus from from the URL text box.
919 urlTextBox.clearFocus();
924 // drawerToggle creates the hamburger icon at the start of the AppBar.
925 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
927 // Get a handle for the progress bar.
928 final ProgressBar progressBar = findViewById(R.id.progress_bar);
930 mainWebView.setWebChromeClient(new WebChromeClient() {
931 // Update the progress bar when a page is loading.
933 public void onProgressChanged(WebView view, int progress) {
934 // Inject the night mode CSS if night mode is enabled.
936 // `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
937 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
938 // `border: none` removes all borders, which can also be used to underline text.
939 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
940 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
941 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
942 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
943 // Initialize a `Handler` to display `mainWebView`.
944 Handler displayWebViewHandler = new Handler();
946 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
947 Runnable displayWebViewRunnable = () -> {
948 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
949 if (progressBar.getVisibility() == View.GONE) {
950 mainWebView.setVisibility(View.VISIBLE);
954 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
955 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
959 // Update the progress bar.
960 progressBar.setProgress(progress);
962 // Set the visibility of the progress bar.
963 if (progress < 100) {
964 // Show the progress bar.
965 progressBar.setVisibility(View.VISIBLE);
967 // Hide the progress bar.
968 progressBar.setVisibility(View.GONE);
970 // Display `mainWebView` if night mode is disabled.
971 // 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
972 // currently enabled.
974 mainWebView.setVisibility(View.VISIBLE);
977 //Stop the swipe to refresh indicator if it is running
978 swipeRefreshLayout.setRefreshing(false);
982 // Set the favorite icon when it changes.
984 public void onReceivedIcon(WebView view, Bitmap icon) {
985 // Only update the favorite icon if the website has finished loading.
986 if (progressBar.getVisibility() == View.GONE) {
987 // Save a copy of the favorite icon.
988 favoriteIconBitmap = icon;
990 // Place the favorite icon in the appBar.
991 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
995 // Save a copy of the title when it changes.
997 public void onReceivedTitle(WebView view, String title) {
998 // Save a copy of the title.
999 webViewTitle = title;
1002 // Enter full screen video.
1004 public void onShowCustomView(View view, CustomViewCallback callback) {
1005 // Set the full screen video flag.
1006 displayingFullScreenVideo = true;
1008 // Pause the ad if this is the free flavor.
1009 if (BuildConfig.FLAVOR.contentEquals("free")) {
1010 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1011 AdHelper.pauseAd(findViewById(R.id.adview));
1014 // Remove the translucent overlays.
1015 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1017 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1018 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1020 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1021 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1022 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1024 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1026 // Set `rootCoordinatorLayout` to fill the entire screen.
1027 rootCoordinatorLayout.setFitsSystemWindows(false);
1029 // Disable the sliding drawers.
1030 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1032 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1033 fullScreenVideoFrameLayout.addView(view);
1034 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1037 // Exit full screen video.
1039 public void onHideCustomView() {
1040 // Unset the full screen video flag.
1041 displayingFullScreenVideo = false;
1043 // Hide `fullScreenVideoFrameLayout`.
1044 fullScreenVideoFrameLayout.removeAllViews();
1045 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1047 // Enable the sliding drawers.
1048 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1050 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1051 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1052 if (hideSystemBarsOnFullscreen) { // Hide everything.
1053 // Remove the translucent navigation setting if it is currently flagged.
1054 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1056 // Remove the translucent status bar overlay.
1057 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1059 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1060 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1062 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1063 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1064 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1066 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1067 } else { // Hide everything except the status and navigation bars.
1068 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1069 rootCoordinatorLayout.setSystemUiVisibility(0);
1071 // Add the translucent status flag if it is unset.
1072 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1074 if (translucentNavigationBarOnFullscreen) {
1075 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1076 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1078 // Set the navigation bar to be black.
1079 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1082 } else { // Switch to normal viewing mode.
1083 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1084 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1088 // Show the `BannerAd` in the free flavor.
1089 if (BuildConfig.FLAVOR.contentEquals("free")) {
1090 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1091 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1094 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1095 rootCoordinatorLayout.setSystemUiVisibility(0);
1097 // Remove the translucent navigation bar flag if it is set.
1098 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1100 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1101 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1103 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1104 rootCoordinatorLayout.setFitsSystemWindows(true);
1107 // Show the ad if this is the free flavor.
1108 if (BuildConfig.FLAVOR.contentEquals("free")) {
1109 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1110 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1116 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1117 // Show the file chooser if the device is running API >= 21.
1118 if (Build.VERSION.SDK_INT >= 21) {
1119 // Store the file path callback.
1120 fileChooserCallback = filePathCallback;
1122 // Create an intent to open a chooser based ont the file chooser parameters.
1123 Intent fileChooserIntent = fileChooserParams.createIntent();
1125 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1126 startActivityForResult(fileChooserIntent, 0);
1132 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1133 registerForContextMenu(mainWebView);
1135 // Allow the downloading of files.
1136 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1137 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1138 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1139 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1141 // Store the variables for future use by `onRequestPermissionsResult()`.
1143 downloadContentDisposition = contentDisposition;
1144 downloadContentLength = contentLength;
1146 // Show a dialog if the user has previously denied the permission.
1147 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1148 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1149 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1151 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1152 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1153 } else { // Show the permission request directly.
1154 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1155 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1157 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1158 // Get a handle for the download file alert dialog.
1159 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1161 // Show the download file alert dialog.
1162 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1166 // Allow pinch to zoom.
1167 mainWebView.getSettings().setBuiltInZoomControls(true);
1169 // Hide zoom controls.
1170 mainWebView.getSettings().setDisplayZoomControls(false);
1172 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1173 mainWebView.getSettings().setUseWideViewPort(true);
1175 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1176 mainWebView.getSettings().setLoadWithOverviewMode(true);
1178 // Explicitly disable geolocation.
1179 mainWebView.getSettings().setGeolocationEnabled(false);
1181 // Initialize cookieManager.
1182 cookieManager = CookieManager.getInstance();
1184 // 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).
1185 customHeaders.put("X-Requested-With", "");
1187 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1188 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1190 // Get the intent that started the app.
1191 final Intent launchingIntent = getIntent();
1193 // Extract the launching intent data as `launchingIntentUriData`.
1194 final Uri launchingIntentUriData = launchingIntent.getData();
1196 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1197 if (launchingIntentUriData != null) {
1198 formattedUrlString = launchingIntentUriData.toString();
1201 // Get a handle for the `Runtime`.
1202 privacyBrowserRuntime = Runtime.getRuntime();
1204 // Store the application's private data directory.
1205 privateDataDirectoryString = getApplicationInfo().dataDir;
1206 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1208 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1209 inFullScreenBrowsingMode = false;
1211 // Initialize the privacy settings variables.
1212 javaScriptEnabled = false;
1213 firstPartyCookiesEnabled = false;
1214 thirdPartyCookiesEnabled = false;
1215 domStorageEnabled = false;
1216 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1219 // Initialize the WebView title.
1220 webViewTitle = getString(R.string.no_title);
1222 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1223 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1224 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1225 assert favoriteIconBitmapDrawable != null;
1226 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1228 // If the favorite icon is null, load the default.
1229 if (favoriteIconBitmap == null) {
1230 favoriteIconBitmap = favoriteIconDefaultBitmap;
1233 // Initialize the user agent array adapter and string array.
1234 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1235 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1237 // Apply the app settings from the shared preferences.
1240 // Instantiate the block list helper.
1241 BlockListHelper blockListHelper = new BlockListHelper();
1243 // Initialize the list of resource requests.
1244 resourceRequests = new ArrayList<>();
1246 // Parse the block lists.
1247 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1248 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1249 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1250 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1251 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1253 // Store the list versions.
1254 easyListVersion = easyList.get(0).get(0)[0];
1255 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1256 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1257 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1258 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1260 // Get a handle for the activity. This is used to update the requests counter while the navigation menu is open.
1261 Activity activity = this;
1263 mainWebView.setWebViewClient(new WebViewClient() {
1264 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1265 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1266 @SuppressWarnings("deprecation")
1268 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1269 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1270 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1271 formattedUrlString = "";
1273 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1274 applyDomainSettings(url, true, false);
1276 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1278 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1279 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1280 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1282 // Parse the url and set it as the data for the intent.
1283 emailIntent.setData(Uri.parse(url));
1285 // Open the email program in a new task instead of as part of Privacy Browser.
1286 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1289 startActivity(emailIntent);
1291 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1293 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1294 // Open the dialer and load the phone number, but wait for the user to place the call.
1295 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1297 // Add the phone number to the intent.
1298 dialIntent.setData(Uri.parse(url));
1300 // Open the dialer in a new task instead of as part of Privacy Browser.
1301 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1304 startActivity(dialIntent);
1306 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1308 } else { // Load a system chooser to select an app that can handle the URL.
1309 // Open an app that can handle the URL.
1310 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1312 // Add the URL to the intent.
1313 genericIntent.setData(Uri.parse(url));
1315 // List all apps that can handle the URL instead of just opening the first one.
1316 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1318 // Open the app in a new task instead of as part of Privacy Browser.
1319 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1321 // Start the app or display a snackbar if no app is available to handle the URL.
1323 startActivity(genericIntent);
1324 } catch (ActivityNotFoundException exception) {
1325 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1328 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1333 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1334 @SuppressWarnings("deprecation")
1336 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1337 // Create an empty web resource response to be used if the resource request is blocked.
1338 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1340 // Reset the whitelist results tracker.
1341 whiteListResultStringArray = null;
1343 // Initialize the third party request tracker.
1344 boolean isThirdPartyRequest = false;
1346 // Initialize the current domain string.
1347 String currentDomain = "";
1349 // Nobody is happy when comparing null strings.
1350 if (!(formattedUrlString == null) && !(url == null)) {
1351 // Get the domain strings to URIs.
1352 Uri currentDomainUri = Uri.parse(formattedUrlString);
1353 Uri requestDomainUri = Uri.parse(url);
1355 // Get the domain host names.
1356 String currentBaseDomain = currentDomainUri.getHost();
1357 String requestBaseDomain = requestDomainUri.getHost();
1359 // Update the current domain variable.
1360 currentDomain = currentBaseDomain;
1362 // Only compare the current base domain and the request base domain if neither is null.
1363 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1364 // Determine the current base domain.
1365 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1366 // Remove the first subdomain.
1367 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1370 // Determine the request base domain.
1371 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1372 // Remove the first subdomain.
1373 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1376 // Update the third party request tracker.
1377 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1381 // Block third-party requests if enabled.
1382 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1383 // Increment the blocked requests counters.
1385 thirdPartyBlockedRequests++;
1387 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1388 activity.runOnUiThread(() -> {
1389 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1390 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1391 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1394 // Add the request to the log.
1395 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1397 // Return an empty web resource response.
1398 return emptyWebResourceResponse;
1401 // Check UltraPrivacy if it is enabled.
1402 if (ultraPrivacyEnabled) {
1403 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1404 // Increment the blocked requests counters.
1406 ultraPrivacyBlockedRequests++;
1408 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1409 activity.runOnUiThread(() -> {
1410 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1411 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1412 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1415 // The resource request was blocked. Return an empty web resource response.
1416 return emptyWebResourceResponse;
1419 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1420 if (whiteListResultStringArray != null) {
1421 // Add a whitelist entry to the resource requests array.
1422 resourceRequests.add(whiteListResultStringArray);
1424 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1429 // Check EasyList if it is enabled.
1430 if (easyListEnabled) {
1431 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1432 // Increment the blocked requests counters.
1434 easyListBlockedRequests++;
1436 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1437 activity.runOnUiThread(() -> {
1438 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1439 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1440 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1443 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1444 whiteListResultStringArray = null;
1446 // The resource request was blocked. Return an empty web resource response.
1447 return emptyWebResourceResponse;
1451 // Check EasyPrivacy if it is enabled.
1452 if (easyPrivacyEnabled) {
1453 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1454 // Increment the blocked requests counters.
1456 easyPrivacyBlockedRequests++;
1458 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1459 activity.runOnUiThread(() -> {
1460 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1461 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1462 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1465 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1466 whiteListResultStringArray = null;
1468 // The resource request was blocked. Return an empty web resource response.
1469 return emptyWebResourceResponse;
1473 // Check Fanboy’s Annoyance List if it is enabled.
1474 if (fanboysAnnoyanceListEnabled) {
1475 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1476 // Increment the blocked requests counters.
1478 fanboysAnnoyanceListBlockedRequests++;
1480 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1481 activity.runOnUiThread(() -> {
1482 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1483 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1484 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1487 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1488 whiteListResultStringArray = null;
1490 // The resource request was blocked. Return an empty web resource response.
1491 return emptyWebResourceResponse;
1493 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1494 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1495 // Increment the blocked requests counters.
1497 fanboysSocialBlockingListBlockedRequests++;
1499 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1500 activity.runOnUiThread(() -> {
1501 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1502 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1503 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1506 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1507 whiteListResultStringArray = null;
1509 // The resource request was blocked. Return an empty web resource response.
1510 return emptyWebResourceResponse;
1514 // Add the request to the log because it hasn't been processed by any of the previous checks.
1515 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1516 resourceRequests.add(whiteListResultStringArray);
1517 } else { // The request didn't match any blocklist entry. Log it as a defult request.
1518 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1521 // The resource request has not been blocked. `return null` loads the requested resource.
1525 // Handle HTTP authentication requests.
1527 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1528 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1529 httpAuthHandler = handler;
1531 // Display the HTTP authentication dialog.
1532 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1533 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1536 // Update the URL in urlTextBox when the page starts to load.
1538 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1539 // Reset the list of resource requests.
1540 resourceRequests.clear();
1542 // Initialize the counters for requests blocked by each blocklist.
1543 blockedRequests = 0;
1544 easyListBlockedRequests = 0;
1545 easyPrivacyBlockedRequests = 0;
1546 fanboysAnnoyanceListBlockedRequests = 0;
1547 fanboysSocialBlockingListBlockedRequests = 0;
1548 ultraPrivacyBlockedRequests = 0;
1549 thirdPartyBlockedRequests = 0;
1551 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1553 mainWebView.setVisibility(View.INVISIBLE);
1556 // Hide the keyboard. `0` indicates no additional flags.
1557 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1559 // Check to see if Privacy Browser is waiting on Orbot.
1560 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1561 // 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.
1562 formattedUrlString = url;
1564 // Display the formatted URL text.
1565 urlTextBox.setText(formattedUrlString);
1567 // Apply text highlighting to `urlTextBox`.
1570 // Apply any custom domain settings if the URL was loaded by navigating history.
1571 if (navigatingHistory) {
1572 // Reset `navigatingHistory`.
1573 navigatingHistory = false;
1575 // Apply the domain settings.
1576 applyDomainSettings(url, true, false);
1579 // 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.
1580 urlIsLoading = true;
1582 // Replace Refresh with Stop if the menu item has been created. (The WebView typically begins loading before the menu items are instantiated.)
1583 if (refreshMenuItem != null) {
1585 refreshMenuItem.setTitle(R.string.stop);
1587 // If the icon is displayed in the AppBar, set it according to the theme.
1588 if (displayAdditionalAppBarIcons) {
1590 refreshMenuItem.setIcon(R.drawable.close_dark);
1592 refreshMenuItem.setIcon(R.drawable.close_light);
1599 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1601 public void onPageFinished(WebView view, String url) {
1602 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1603 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1604 cookieManager.flush();
1607 // Update the Refresh menu item if it has been created.
1608 if (refreshMenuItem != null) {
1609 // Reset the Refresh title.
1610 refreshMenuItem.setTitle(R.string.refresh);
1612 // If the icon is displayed in the AppBar, reset it according to the theme.
1613 if (displayAdditionalAppBarIcons) {
1615 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1617 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1622 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1623 urlIsLoading = false;
1625 // Clear the cache and history if Incognito Mode is enabled.
1626 if (incognitoModeEnabled) {
1627 // Clear the cache. `true` includes disk files.
1628 mainWebView.clearCache(true);
1630 // Clear the back/forward history.
1631 mainWebView.clearHistory();
1633 // Manually delete cache folders.
1635 // Delete the main cache directory.
1636 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1638 // Delete the secondary `Service Worker` cache directory.
1639 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1640 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1641 } catch (IOException e) {
1642 // Do nothing if an error is thrown.
1646 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1647 if (!waitingForOrbot) {
1648 // Check to see if `WebView` has set `url` to be `about:blank`.
1649 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1650 // Set `formattedUrlString` to `""`.
1651 formattedUrlString = "";
1653 urlTextBox.setText(formattedUrlString);
1655 // Request focus for `urlTextBox`.
1656 urlTextBox.requestFocus();
1658 // Display the keyboard.
1659 inputMethodManager.showSoftInput(urlTextBox, 0);
1661 // Apply the domain settings. This clears any settings from the previous domain.
1662 applyDomainSettings(formattedUrlString, true, false);
1663 } else { // `WebView` has loaded a webpage.
1664 // Set `formattedUrlString`.
1665 formattedUrlString = url;
1667 // Only update `urlTextBox` if the user is not typing in it.
1668 if (!urlTextBox.hasFocus()) {
1669 // Display the formatted URL text.
1670 urlTextBox.setText(formattedUrlString);
1672 // Apply text highlighting to `urlTextBox`.
1677 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1678 sslCertificate = mainWebView.getCertificate();
1680 // 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.
1681 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1682 // Initialize the current SSL certificate variables.
1683 String currentWebsiteIssuedToCName = "";
1684 String currentWebsiteIssuedToOName = "";
1685 String currentWebsiteIssuedToUName = "";
1686 String currentWebsiteIssuedByCName = "";
1687 String currentWebsiteIssuedByOName = "";
1688 String currentWebsiteIssuedByUName = "";
1689 Date currentWebsiteSslStartDate = null;
1690 Date currentWebsiteSslEndDate = null;
1693 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1694 if (sslCertificate != null) {
1695 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1696 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1697 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1698 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1699 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1700 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1701 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1702 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1705 // 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`.
1706 String currentWebsiteSslStartDateString = "";
1707 String currentWebsiteSslEndDateString = "";
1708 String pinnedDomainSslStartDateString = "";
1709 String pinnedDomainSslEndDateString = "";
1711 // Convert the `Dates` to `Strings` if they are not `null`.
1712 if (currentWebsiteSslStartDate != null) {
1713 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1716 if (currentWebsiteSslEndDate != null) {
1717 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1720 if (pinnedDomainSslStartDate != null) {
1721 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1724 if (pinnedDomainSslEndDate != null) {
1725 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1728 // Check to see if the pinned SSL certificate matches the current website certificate.
1729 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1730 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1731 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1732 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1733 // The pinned SSL certificate doesn't match the current domain certificate.
1734 //Display the pinned SSL certificate mismatch `AlertDialog`.
1735 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1736 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1742 // Handle SSL Certificate errors.
1744 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1745 // Get the current website SSL certificate.
1746 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1748 // Extract the individual pieces of information from the current website SSL certificate.
1749 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1750 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1751 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1752 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1753 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1754 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1755 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1756 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1758 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1759 if (pinnedDomainSslCertificate &&
1760 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1761 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1762 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1763 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1764 // An SSL certificate is pinned and matches the current domain certificate.
1765 // Proceed to the website without displaying an error.
1767 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1768 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1769 sslErrorHandler = handler;
1771 // Display the SSL error `AlertDialog`.
1772 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1773 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1778 // Load the website if not waiting for Orbot to connect.
1779 if (!waitingForOrbot) {
1780 loadUrl(formattedUrlString);
1785 protected void onNewIntent(Intent intent) {
1786 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1789 // Check to see if the intent contains a new URL.
1790 if (intent.getData() != null) {
1791 // Get the intent data.
1792 final Uri intentUriData = intent.getData();
1794 // Load the website.
1795 loadUrl(intentUriData.toString());
1797 // Close the navigation drawer if it is open.
1798 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1799 drawerLayout.closeDrawer(GravityCompat.START);
1802 // Close the bookmarks drawer if it is open.
1803 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1804 drawerLayout.closeDrawer(GravityCompat.END);
1807 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1808 mainWebView.requestFocus();
1813 public void onRestart() {
1814 // Run the default commands.
1817 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1818 if (proxyThroughOrbot) {
1819 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1820 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1822 // Send the intent to the Orbot package.
1823 orbotIntent.setPackage("org.torproject.android");
1826 sendBroadcast(orbotIntent);
1829 // Apply the app settings if returning from the Settings activity..
1830 if (reapplyAppSettingsOnRestart) {
1831 // Apply the app settings.
1834 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1835 if (reloadOnRestart) {
1836 // Reload `mainWebView`.
1837 mainWebView.reload();
1839 // Reset `reloadOnRestartBoolean`.
1840 reloadOnRestart = false;
1843 // Reset the return from settings flag.
1844 reapplyAppSettingsOnRestart = false;
1847 // Apply the domain settings if returning from the Domains activity.
1848 if (reapplyDomainSettingsOnRestart) {
1849 // Reapply the domain settings.
1850 applyDomainSettings(formattedUrlString, false, true);
1852 // Reset `reapplyDomainSettingsOnRestart`.
1853 reapplyDomainSettingsOnRestart = false;
1856 // Load the URL on restart to apply changes to night mode.
1857 if (loadUrlOnRestart) {
1858 // Load the current `formattedUrlString`.
1859 loadUrl(formattedUrlString);
1861 // Reset `loadUrlOnRestart.
1862 loadUrlOnRestart = false;
1865 // Update the bookmarks drawer if returning from the Bookmarks activity.
1866 if (restartFromBookmarksActivity) {
1867 // Close the bookmarks drawer.
1868 drawerLayout.closeDrawer(GravityCompat.END);
1870 // Reload the bookmarks drawer.
1871 loadBookmarksFolder();
1873 // Reset `restartFromBookmarksActivity`.
1874 restartFromBookmarksActivity = false;
1877 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1878 updatePrivacyIcons(true);
1881 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1883 public void onResume() {
1884 // Run the default commands.
1887 // Resume JavaScript (if enabled).
1888 mainWebView.resumeTimers();
1890 // Resume `mainWebView`.
1891 mainWebView.onResume();
1893 // Resume the adView for the free flavor.
1894 if (BuildConfig.FLAVOR.contentEquals("free")) {
1896 AdHelper.resumeAd(findViewById(R.id.adview));
1899 // Display a message to the user if waiting for Orbot.
1900 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1901 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1902 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1905 if (displayingFullScreenVideo) {
1906 // Remove the translucent overlays.
1907 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1909 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1910 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1912 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1913 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1914 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1916 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1921 public void onPause() {
1922 // Run the default commands.
1925 // Pause `mainWebView`.
1926 mainWebView.onPause();
1928 // Stop all JavaScript.
1929 mainWebView.pauseTimers();
1931 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1932 if (BuildConfig.FLAVOR.contentEquals("free")) {
1934 AdHelper.pauseAd(findViewById(R.id.adview));
1939 public void onDestroy() {
1940 // Unregister the Orbot status broadcast receiver.
1941 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1943 // Run the default commands.
1948 public boolean onCreateOptionsMenu(Menu menu) {
1949 // Inflate the menu; this adds items to the action bar if it is present.
1950 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1952 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1955 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1956 updatePrivacyIcons(false);
1958 // Get handles for the menu items.
1959 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1960 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1961 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1962 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1963 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1964 refreshMenuItem = menu.findItem(R.id.refresh);
1965 blocklistsMenuItem = menu.findItem(R.id.blocklists);
1966 easyListMenuItem = menu.findItem(R.id.easylist);
1967 easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1968 fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1969 fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1970 ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1971 blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1972 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1974 // Only display third-party cookies if API >= 21
1975 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1977 // Only display the form data menu items if the API < 26.
1978 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1979 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1981 // Only show Ad Consent if this is the free flavor.
1982 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1984 // Get the shared preference values.
1985 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1987 // Get the status of the additional AppBar icons.
1988 displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1990 // 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.
1991 if (displayAdditionalAppBarIcons) {
1992 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1993 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1994 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1995 } else { //Do not display the additional icons.
1996 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1997 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1998 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2001 // Replace Refresh with Stop if a URL is already loading.
2004 refreshMenuItem.setTitle(R.string.stop);
2006 // If the icon is displayed in the AppBar, set it according to the theme.
2007 if (displayAdditionalAppBarIcons) {
2009 refreshMenuItem.setIcon(R.drawable.close_dark);
2011 refreshMenuItem.setIcon(R.drawable.close_light);
2020 public boolean onPrepareOptionsMenu(Menu menu) {
2021 // Get handles for the menu items.
2022 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2023 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2024 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2025 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2026 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
2027 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2028 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2029 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2030 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
2031 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2032 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
2033 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2035 // Set the text for the domain menu item.
2036 if (domainSettingsApplied) {
2037 addOrEditDomain.setTitle(R.string.edit_domain_settings);
2039 addOrEditDomain.setTitle(R.string.add_domain_settings);
2042 // Set the status of the menu item checkboxes.
2043 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2044 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2045 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2046 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
2047 easyListMenuItem.setChecked(easyListEnabled);
2048 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
2049 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
2050 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
2051 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
2052 blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
2053 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
2054 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2056 // Enable third-party cookies if first-party cookies are enabled.
2057 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2059 // Enable DOM Storage if JavaScript is enabled.
2060 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2062 // Enable Clear Cookies if there are any.
2063 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2065 // Get a count of the number of files in the Local Storage directory.
2066 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2067 int localStorageDirectoryNumberOfFiles = 0;
2068 if (localStorageDirectory.exists()) {
2069 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2072 // Get a count of the number of files in the IndexedDB directory.
2073 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2074 int indexedDBDirectoryNumberOfFiles = 0;
2075 if (indexedDBDirectory.exists()) {
2076 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2079 // Enable Clear DOM Storage if there is any.
2080 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2082 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
2083 if (Build.VERSION.SDK_INT < 26) {
2084 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2085 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2087 // Disable clear form data because it is not supported on current version of Android.
2088 clearFormDataMenuItem.setEnabled(false);
2091 // Enable Clear Data if any of the submenu items are enabled.
2092 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2094 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2095 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2097 // Initialize the display names for the blocklists with the number of blocked requests.
2098 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
2099 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2100 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2101 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2102 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2103 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2104 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2106 // Initialize font size variables.
2107 int fontSize = mainWebView.getSettings().getTextZoom();
2108 String fontSizeTitle;
2109 MenuItem selectedFontSizeMenuItem;
2111 // Prepare the font size title and current size menu item.
2114 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2115 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2119 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2120 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2124 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2125 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2129 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2130 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2134 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2135 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2139 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2140 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2144 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2145 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2149 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2150 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2154 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2155 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2159 // Set the font size title and select the current size menu item.
2160 fontSizeMenuItem.setTitle(fontSizeTitle);
2161 selectedFontSizeMenuItem.setChecked(true);
2163 // Run all the other default commands.
2164 super.onPrepareOptionsMenu(menu);
2166 // Display the menu.
2171 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2172 @SuppressLint("SetJavaScriptEnabled")
2173 // removeAllCookies is deprecated, but it is required for API < 21.
2174 @SuppressWarnings("deprecation")
2175 public boolean onOptionsItemSelected(MenuItem menuItem) {
2176 // Get the selected menu item ID.
2177 int menuItemId = menuItem.getItemId();
2179 // Set the commands that relate to the menu entries.
2180 switch (menuItemId) {
2181 case R.id.toggle_javascript:
2182 // Switch the status of javaScriptEnabled.
2183 javaScriptEnabled = !javaScriptEnabled;
2185 // Apply the new JavaScript status.
2186 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2188 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2189 updatePrivacyIcons(true);
2191 // Display a `Snackbar`.
2192 if (javaScriptEnabled) { // JavaScrip is enabled.
2193 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2194 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2195 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2196 } else { // Privacy mode.
2197 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2200 // Reload the WebView.
2201 mainWebView.reload();
2204 case R.id.add_or_edit_domain:
2205 if (domainSettingsApplied) { // Edit the current domain settings.
2206 // Reapply the domain settings on returning to `MainWebViewActivity`.
2207 reapplyDomainSettingsOnRestart = true;
2208 currentDomainName = "";
2210 // Create an intent to launch the domains activity.
2211 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2213 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2214 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2215 domainsIntent.putExtra("closeOnBack", true);
2218 startActivity(domainsIntent);
2219 } else { // Add a new domain.
2220 // Apply the new domain settings on returning to `MainWebViewActivity`.
2221 reapplyDomainSettingsOnRestart = true;
2222 currentDomainName = "";
2224 // Get the current domain
2225 Uri currentUri = Uri.parse(formattedUrlString);
2226 String currentDomain = currentUri.getHost();
2228 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2229 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2231 // Create the domain and store the database ID.
2232 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2234 // Create an intent to launch the domains activity.
2235 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2237 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2238 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2239 domainsIntent.putExtra("closeOnBack", true);
2242 startActivity(domainsIntent);
2246 case R.id.toggle_first_party_cookies:
2247 // Switch the status of firstPartyCookiesEnabled.
2248 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2250 // Update the menu checkbox.
2251 menuItem.setChecked(firstPartyCookiesEnabled);
2253 // Apply the new cookie status.
2254 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2256 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2257 updatePrivacyIcons(true);
2259 // Display a `Snackbar`.
2260 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2261 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2262 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2263 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2264 } else { // Privacy mode.
2265 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2268 // Reload the WebView.
2269 mainWebView.reload();
2272 case R.id.toggle_third_party_cookies:
2273 if (Build.VERSION.SDK_INT >= 21) {
2274 // Switch the status of thirdPartyCookiesEnabled.
2275 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2277 // Update the menu checkbox.
2278 menuItem.setChecked(thirdPartyCookiesEnabled);
2280 // Apply the new cookie status.
2281 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2283 // Display a `Snackbar`.
2284 if (thirdPartyCookiesEnabled) {
2285 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2287 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2290 // Reload the WebView.
2291 mainWebView.reload();
2292 } // Else do nothing because SDK < 21.
2295 case R.id.toggle_dom_storage:
2296 // Switch the status of domStorageEnabled.
2297 domStorageEnabled = !domStorageEnabled;
2299 // Update the menu checkbox.
2300 menuItem.setChecked(domStorageEnabled);
2302 // Apply the new DOM Storage status.
2303 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2305 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2306 updatePrivacyIcons(true);
2308 // Display a `Snackbar`.
2309 if (domStorageEnabled) {
2310 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2312 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2315 // Reload the WebView.
2316 mainWebView.reload();
2319 // Form data can be removed once the minimum API >= 26.
2320 case R.id.toggle_save_form_data:
2321 // Switch the status of saveFormDataEnabled.
2322 saveFormDataEnabled = !saveFormDataEnabled;
2324 // Update the menu checkbox.
2325 menuItem.setChecked(saveFormDataEnabled);
2327 // Apply the new form data status.
2328 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2330 // Display a `Snackbar`.
2331 if (saveFormDataEnabled) {
2332 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2334 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2337 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2338 updatePrivacyIcons(true);
2340 // Reload the WebView.
2341 mainWebView.reload();
2344 case R.id.clear_cookies:
2345 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2346 .setAction(R.string.undo, v -> {
2347 // Do nothing because everything will be handled by `onDismissed()` below.
2349 .addCallback(new Snackbar.Callback() {
2351 public void onDismissed(Snackbar snackbar, int event) {
2353 // The user pushed the `Undo` button.
2354 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2358 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2360 // `cookieManager.removeAllCookie()` varies by SDK.
2361 if (Build.VERSION.SDK_INT < 21) {
2362 cookieManager.removeAllCookie();
2364 // `null` indicates no callback.
2365 cookieManager.removeAllCookies(null);
2373 case R.id.clear_dom_storage:
2374 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2375 .setAction(R.string.undo, v -> {
2376 // Do nothing because everything will be handled by `onDismissed()` below.
2378 .addCallback(new Snackbar.Callback() {
2380 public void onDismissed(Snackbar snackbar, int event) {
2382 // The user pushed the `Undo` button.
2383 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2387 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2389 // Delete the DOM Storage.
2390 WebStorage webStorage = WebStorage.getInstance();
2391 webStorage.deleteAllData();
2393 // Manually delete the DOM storage files and directories.
2395 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2396 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2398 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2399 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2400 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2401 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2402 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2403 } catch (IOException e) {
2404 // Do nothing if an error is thrown.
2412 // Form data can be remove once the minimum API >= 26.
2413 case R.id.clear_form_data:
2414 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2415 .setAction(R.string.undo, v -> {
2416 // Do nothing because everything will be handled by `onDismissed()` below.
2418 .addCallback(new Snackbar.Callback() {
2420 public void onDismissed(Snackbar snackbar, int event) {
2422 // The user pushed the `Undo` button.
2423 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2427 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2429 // Delete the form data.
2430 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2431 mainWebViewDatabase.clearFormData();
2438 case R.id.font_size_twenty_five_percent:
2439 mainWebView.getSettings().setTextZoom(25);
2442 case R.id.font_size_fifty_percent:
2443 mainWebView.getSettings().setTextZoom(50);
2446 case R.id.font_size_seventy_five_percent:
2447 mainWebView.getSettings().setTextZoom(75);
2450 case R.id.font_size_one_hundred_percent:
2451 mainWebView.getSettings().setTextZoom(100);
2454 case R.id.font_size_one_hundred_twenty_five_percent:
2455 mainWebView.getSettings().setTextZoom(125);
2458 case R.id.font_size_one_hundred_fifty_percent:
2459 mainWebView.getSettings().setTextZoom(150);
2462 case R.id.font_size_one_hundred_seventy_five_percent:
2463 mainWebView.getSettings().setTextZoom(175);
2466 case R.id.font_size_two_hundred_percent:
2467 mainWebView.getSettings().setTextZoom(200);
2470 case R.id.swipe_to_refresh:
2471 // Toggle swipe to refresh.
2472 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2475 case R.id.display_images:
2476 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2477 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2478 mainWebView.reload();
2479 } else { // Images are not currently loaded automatically.
2480 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2483 // Set `onTheFlyDisplayImagesSet`.
2484 onTheFlyDisplayImagesSet = true;
2487 case R.id.view_source:
2488 // Launch the View Source activity.
2489 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2490 startActivity(viewSourceIntent);
2494 // Toggle the EasyList status.
2495 easyListEnabled = !easyListEnabled;
2497 // Update the menu checkbox.
2498 menuItem.setChecked(easyListEnabled);
2500 // Reload the main WebView.
2501 mainWebView.reload();
2504 case R.id.easyprivacy:
2505 // Toggle the EasyPrivacy status.
2506 easyPrivacyEnabled = !easyPrivacyEnabled;
2508 // Update the menu checkbox.
2509 menuItem.setChecked(easyPrivacyEnabled);
2511 // Reload the main WebView.
2512 mainWebView.reload();
2515 case R.id.fanboys_annoyance_list:
2516 // Toggle Fanboy's Annoyance List status.
2517 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2519 // Update the menu checkbox.
2520 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2522 // Update the staus of Fanboy's Social Blocking List.
2523 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2524 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2526 // Reload the main WebView.
2527 mainWebView.reload();
2530 case R.id.fanboys_social_blocking_list:
2531 // Toggle Fanboy's Social Blocking List status.
2532 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2534 // Update the menu checkbox.
2535 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2537 // Reload the main WebView.
2538 mainWebView.reload();
2541 case R.id.ultraprivacy:
2542 // Toggle the UltraPrivacy status.
2543 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2545 // Update the menu checkbox.
2546 menuItem.setChecked(ultraPrivacyEnabled);
2548 // Reload the main WebView.
2549 mainWebView.reload();
2552 case R.id.block_all_third_party_requests:
2553 //Toggle the third-party requests blocker status.
2554 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2556 // Update the menu checkbox.
2557 menuItem.setChecked(blockAllThirdPartyRequests);
2559 // Reload the main WebView.
2560 mainWebView.reload();
2564 // Setup the share string.
2565 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2567 // Create the share intent.
2568 Intent shareIntent = new Intent();
2569 shareIntent.setAction(Intent.ACTION_SEND);
2570 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2571 shareIntent.setType("text/plain");
2574 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2577 case R.id.find_on_page:
2578 // Hide the URL app bar.
2579 supportAppBar.setVisibility(View.GONE);
2581 // Show the Find on Page `RelativeLayout`.
2582 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2584 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2585 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2586 findOnPageEditText.postDelayed(() -> {
2587 // Set the focus on `findOnPageEditText`.
2588 findOnPageEditText.requestFocus();
2590 // Display the keyboard. `0` sets no input flags.
2591 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2596 // Get a `PrintManager` instance.
2597 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2599 // Convert `mainWebView` to `printDocumentAdapter`.
2600 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2602 // Remove the lint error below that `printManager` might be `null`.
2603 assert printManager != null;
2605 // Print the document. The print attributes are `null`.
2606 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2609 case R.id.add_to_homescreen:
2610 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2611 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2612 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2614 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2618 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2619 // Reload the WebView.
2620 mainWebView.reload();
2621 } else { // The stop button was pushed.
2622 // Stop the loading of the WebView.
2623 mainWebView.stopLoading();
2627 case R.id.ad_consent:
2628 // Display the ad consent dialog.
2629 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2630 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2634 // Don't consume the event.
2635 return super.onOptionsItemSelected(menuItem);
2639 // removeAllCookies is deprecated, but it is required for API < 21.
2640 @SuppressWarnings("deprecation")
2642 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2643 int menuItemId = menuItem.getItemId();
2645 switch (menuItemId) {
2651 if (mainWebView.canGoBack()) {
2652 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2653 formattedUrlString = "";
2655 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2656 navigatingHistory = true;
2658 // Load the previous website in the history.
2659 mainWebView.goBack();
2664 if (mainWebView.canGoForward()) {
2665 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2666 formattedUrlString = "";
2668 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2669 navigatingHistory = true;
2671 // Load the next website in the history.
2672 mainWebView.goForward();
2677 // Get the `WebBackForwardList`.
2678 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2680 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2681 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2682 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2686 // Launch the requests activity.
2687 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2688 startActivity(requestsIntent);
2691 case R.id.downloads:
2692 // Launch the system Download Manager.
2693 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2695 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2696 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2698 startActivity(downloadManagerIntent);
2702 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2703 reapplyDomainSettingsOnRestart = true;
2704 currentDomainName = "";
2706 // Launch the domains activity.
2707 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2708 startActivity(domainsIntent);
2712 // Set the flag to reapply app settings on restart when returning from Settings.
2713 reapplyAppSettingsOnRestart = true;
2715 // Set the flag to reapply the domain settings on restart when returning from Settings.
2716 reapplyDomainSettingsOnRestart = true;
2717 currentDomainName = "";
2719 // Launch the settings activity.
2720 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2721 startActivity(settingsIntent);
2725 // Launch `GuideActivity`.
2726 Intent guideIntent = new Intent(this, GuideActivity.class);
2727 startActivity(guideIntent);
2731 // Launch `AboutActivity`.
2732 Intent aboutIntent = new Intent(this, AboutActivity.class);
2733 startActivity(aboutIntent);
2736 case R.id.clearAndExit:
2737 // Get a handle for `sharedPreferences`. `this` references the current context.
2738 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2740 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2743 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2744 // The command to remove cookies changed slightly in API 21.
2745 if (Build.VERSION.SDK_INT >= 21) {
2746 cookieManager.removeAllCookies(null);
2748 cookieManager.removeAllCookie();
2751 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2753 // We have to use two commands because `Runtime.exec()` does not like `*`.
2754 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2755 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2756 } catch (IOException e) {
2757 // Do nothing if an error is thrown.
2761 // Clear DOM storage.
2762 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2763 // Ask `WebStorage` to clear the DOM storage.
2764 WebStorage webStorage = WebStorage.getInstance();
2765 webStorage.deleteAllData();
2767 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2769 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2770 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2772 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2773 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2774 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2775 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2776 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2777 } catch (IOException e) {
2778 // Do nothing if an error is thrown.
2782 // Clear form data if the API < 26.
2783 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2784 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2785 webViewDatabase.clearFormData();
2787 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2789 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2790 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2791 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2792 } catch (IOException e) {
2793 // Do nothing if an error is thrown.
2798 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2799 // `true` includes disk files.
2800 mainWebView.clearCache(true);
2802 // Manually delete the cache directories.
2804 // Delete the main cache directory.
2805 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2807 // Delete the secondary `Service Worker` cache directory.
2808 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2809 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2810 } catch (IOException e) {
2811 // Do nothing if an error is thrown.
2815 // Clear SSL certificate preferences.
2816 mainWebView.clearSslPreferences();
2818 // Clear the back/forward history.
2819 mainWebView.clearHistory();
2821 // Clear `formattedUrlString`.
2822 formattedUrlString = null;
2824 // Clear `customHeaders`.
2825 customHeaders.clear();
2827 // Detach all views from `mainWebViewRelativeLayout`.
2828 mainWebViewRelativeLayout.removeAllViews();
2830 // Destroy the internal state of `mainWebView`.
2831 mainWebView.destroy();
2833 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2834 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2835 if (clearEverything) {
2837 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2838 } catch (IOException e) {
2839 // Do nothing if an error is thrown.
2843 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2844 if (Build.VERSION.SDK_INT >= 21) {
2845 finishAndRemoveTask();
2850 // Remove the terminated program from RAM. The status code is `0`.
2855 // Close the navigation drawer.
2856 drawerLayout.closeDrawer(GravityCompat.START);
2861 public void onPostCreate(Bundle savedInstanceState) {
2862 super.onPostCreate(savedInstanceState);
2864 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2865 drawerToggle.syncState();
2869 public void onConfigurationChanged(Configuration newConfig) {
2870 super.onConfigurationChanged(newConfig);
2872 // Reload the ad for the free flavor if we not in full screen mode.
2873 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2874 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2875 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2878 // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug:
2879 // https://code.google.com/p/android/issues/detail?id=20493#c8
2880 // ActivityCompat.invalidateOptionsMenu(this);
2884 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2885 // Store the `HitTestResult`.
2886 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2889 final String imageUrl;
2890 final String linkUrl;
2892 // Get a handle for the `ClipboardManager`.
2893 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2895 // Remove the lint errors below that `clipboardManager` might be `null`.
2896 assert clipboardManager != null;
2898 switch (hitTestResult.getType()) {
2899 // `SRC_ANCHOR_TYPE` is a link.
2900 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2901 // Get the target URL.