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 // The blocklist variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
344 private boolean easyListEnabled;
345 private boolean easyPrivacyEnabled;
346 private boolean fanboysAnnoyanceListEnabled;
347 private boolean fanboysSocialBlockingListEnabled;
348 private boolean ultraPrivacyEnabled;
350 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
351 private Runtime privacyBrowserRuntime;
353 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
354 private boolean proxyThroughOrbot;
356 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
357 private boolean incognitoModeEnabled;
359 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
360 private boolean fullScreenBrowsingModeEnabled;
362 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
363 private boolean inFullScreenBrowsingMode;
365 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
366 private boolean hideSystemBarsOnFullscreen;
368 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
369 private boolean translucentNavigationBarOnFullscreen;
371 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
372 private boolean reapplyDomainSettingsOnRestart;
374 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
375 private boolean reapplyAppSettingsOnRestart;
377 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
378 private boolean displayingFullScreenVideo;
380 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
381 private String currentDomainName;
383 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
384 private boolean ignorePinnedSslCertificate;
386 // `orbotStatusBroadcastReciever` is used in `onCreate()` and `onDestroy()`.
387 private BroadcastReceiver orbotStatusBroadcastReceiver;
389 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyAppSettings()`.
390 private boolean waitingForOrbot;
392 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
393 private boolean domainSettingsApplied;
395 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
396 private int displayWebpageImagesInt;
398 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
399 private boolean onTheFlyDisplayImagesSet;
401 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
402 private String waitingForOrbotHTMLString;
404 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
405 private String privateDataDirectoryString;
407 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
408 private LinearLayout findOnPageLinearLayout;
410 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
411 private EditText findOnPageEditText;
413 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
414 private Menu mainMenu;
416 // `refreshMenuItem` is used in `onCreate()` and `onCreateOptionsMenu()`.
417 private MenuItem refreshMenuItem;
419 // The blocklist menu items are used in `onCreate()` and `onCreateOptionsMenu()`.
420 MenuItem easyListMenuItem;
421 MenuItem easyPrivacyMenuItem;
422 MenuItem fanboysAnnoyanceListMenuItem;
423 MenuItem fanboysSocialBlockingListMenuItem;
424 MenuItem ultraPrivacyMenuItem;
425 MenuItem blockAllThirdParyRequestsMenuItem;
427 // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
428 private boolean displayAdditionalAppBarIcons;
430 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
431 private ActionBarDrawerToggle drawerToggle;
433 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
434 private Toolbar supportAppBar;
436 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
437 private EditText urlTextBox;
439 // The color spans are used in `onCreate()` and `highlightUrlText()`.
440 private ForegroundColorSpan redColorSpan;
441 private ForegroundColorSpan initialGrayColorSpan;
442 private ForegroundColorSpan finalGrayColorSpan;
444 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
445 private SslErrorHandler sslErrorHandler;
447 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
448 private static HttpAuthHandler httpAuthHandler;
450 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
451 private InputMethodManager inputMethodManager;
453 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
454 private RelativeLayout mainWebViewRelativeLayout;
456 // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
457 private boolean urlIsLoading;
459 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
460 private boolean pinnedDomainSslCertificate;
462 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
463 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
465 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
466 private ListView bookmarksListView;
468 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
469 private TextView bookmarksTitleTextView;
471 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
472 private Cursor bookmarksCursor;
474 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
475 private CursorAdapter bookmarksCursorAdapter;
477 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
478 private String oldFolderNameString;
480 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
481 private ValueCallback<Uri[]> fileChooserCallback;
483 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
484 private String downloadUrl;
485 private String downloadContentDisposition;
486 private long downloadContentLength;
488 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
489 private String downloadImageUrl;
491 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
492 private ArrayAdapter<CharSequence> userAgentNamesArray;
493 private String[] userAgentDataArray;
495 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
496 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
497 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
500 // 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.
501 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
502 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
503 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
504 @SuppressWarnings("deprecation")
505 protected void onCreate(Bundle savedInstanceState) {
506 // Get a handle for the shared preferences.
507 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
509 // Get the theme and screenshot preferences.
510 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
511 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
513 // Disable screenshots if not allowed.
514 if (!allowScreenshots) {
515 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
518 // Set the activity theme.
520 setTheme(R.style.PrivacyBrowserDark);
522 setTheme(R.style.PrivacyBrowserLight);
525 // Run the default commands.
526 super.onCreate(savedInstanceState);
528 // Set the content view.
529 setContentView(R.layout.main_drawerlayout);
531 // Get a handle for `inputMethodManager`.
532 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
534 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
535 supportAppBar = findViewById(R.id.app_bar);
536 setSupportActionBar(supportAppBar);
537 appBar = getSupportActionBar();
539 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
540 assert appBar != null;
542 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
543 appBar.setCustomView(R.layout.url_app_bar);
544 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
546 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
547 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
548 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
549 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
551 // Get a handle for `urlTextBox`.
552 urlTextBox = findViewById(R.id.url_edittext);
554 // Remove the formatting from `urlTextBar` when the user is editing the text.
555 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
556 if (hasFocus) { // The user is editing `urlTextBox`.
557 // Remove the highlighting.
558 urlTextBox.getText().removeSpan(redColorSpan);
559 urlTextBox.getText().removeSpan(initialGrayColorSpan);
560 urlTextBox.getText().removeSpan(finalGrayColorSpan);
561 } else { // The user has stopped editing `urlTextBox`.
562 // Reapply the highlighting.
567 // Set the go button on the keyboard to load the URL in `urlTextBox`.
568 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
569 // If the event is a key-down event on the `enter` button, load the URL.
570 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
571 // Load the URL into the mainWebView and consume the event.
573 loadUrlFromTextBox();
574 } catch (UnsupportedEncodingException e) {
577 // If the enter key was pressed, consume the event.
580 // If any other key was pressed, do not consume the event.
585 // Set `waitingForOrbotHTMLString`.
586 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
588 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
589 currentDomainName = "";
590 orbotStatus = "unknown";
591 waitingForOrbot = false;
593 // Create an Orbot status `BroadcastReceiver`.
594 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
596 public void onReceive(Context context, Intent intent) {
597 // Store the content of the status message in `orbotStatus`.
598 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
600 // If we are waiting on Orbot, load the website now that Orbot is connected.
601 if (orbotStatus.equals("ON") && waitingForOrbot) {
602 // Reset `waitingForOrbot`.
603 waitingForOrbot = false;
605 // Load `formattedUrlString
606 loadUrl(formattedUrlString);
611 // Register `orbotStatusBroadcastReceiver` on `this` context.
612 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
614 // Get handles for views that need to be accessed.
615 drawerLayout = findViewById(R.id.drawerlayout);
616 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
617 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
618 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
619 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
620 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
621 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
622 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
623 mainWebView = findViewById(R.id.main_webview);
624 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
625 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
626 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
627 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
628 favoriteIconImageView = findViewById(R.id.favorite_icon);
630 // 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.
632 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
633 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
634 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
635 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
637 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
638 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
639 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
640 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
643 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
644 launchBookmarksActivityFab.setOnClickListener(v -> {
645 // Create an intent to launch the bookmarks activity.
646 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
648 // Include the current folder with the `Intent`.
649 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
652 startActivity(bookmarksIntent);
655 // Set the create new bookmark folder FAB to display an alert dialog.
656 createBookmarkFolderFab.setOnClickListener(v -> {
657 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
658 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
659 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
662 // Set the create new bookmark FAB to display an alert dialog.
663 createBookmarkFab.setOnClickListener(view -> {
664 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
665 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
666 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
669 // Create a double-tap listener to toggle full-screen mode.
670 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
671 // Override `onDoubleTap()`. All other events are handled using the default settings.
673 public boolean onDoubleTap(MotionEvent event) {
674 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
675 // Toggle `inFullScreenBrowsingMode`.
676 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
678 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
679 // Hide the `appBar`.
682 // Hide the banner ad in the free flavor.
683 if (BuildConfig.FLAVOR.contentEquals("free")) {
684 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
685 AdHelper.hideAd(findViewById(R.id.adview));
688 // Modify the system bars.
689 if (hideSystemBarsOnFullscreen) { // Hide everything.
690 // Remove the translucent overlays.
691 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
693 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
694 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
696 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
697 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
698 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
700 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
702 // Set `rootCoordinatorLayout` to fill the whole screen.
703 rootCoordinatorLayout.setFitsSystemWindows(false);
704 } else { // Hide everything except the status and navigation bars.
705 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
706 rootCoordinatorLayout.setFitsSystemWindows(false);
708 // 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.
709 if (translucentNavigationBarOnFullscreen) {
710 // Set the navigation bar to be translucent.
711 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
714 } else { // Switch to normal viewing mode.
715 // Show the `appBar`.
718 // Show the `BannerAd` in the free flavor.
719 if (BuildConfig.FLAVOR.contentEquals("free")) {
720 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
721 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
724 // Remove the translucent navigation bar flag if it is set.
725 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
727 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
728 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
730 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
731 rootCoordinatorLayout.setSystemUiVisibility(0);
733 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
734 rootCoordinatorLayout.setFitsSystemWindows(true);
737 // Consume the double-tap.
739 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
745 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
746 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
747 // Call `performClick()` on the view, which is required for accessibility.
750 // Send the `event` to `gestureDetector`.
751 return gestureDetector.onTouchEvent(event);
754 // Update `findOnPageCountTextView`.
755 mainWebView.setFindListener(new WebView.FindListener() {
756 // Get a handle for `findOnPageCountTextView`.
757 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
760 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
761 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
762 // Set `findOnPageCountTextView` to `0/0`.
763 findOnPageCountTextView.setText(R.string.zero_of_zero);
764 } else if (isDoneCounting) { // There are matches.
765 // `activeMatchOrdinal` is zero-based.
766 int activeMatch = activeMatchOrdinal + 1;
768 // Build the match string.
769 String matchString = activeMatch + "/" + numberOfMatches;
771 // Set `findOnPageCountTextView`.
772 findOnPageCountTextView.setText(matchString);
777 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
778 findOnPageEditText.addTextChangedListener(new TextWatcher() {
780 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
785 public void onTextChanged(CharSequence s, int start, int before, int count) {
790 public void afterTextChanged(Editable s) {
791 // Search for the text in `mainWebView`.
792 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
796 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
797 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
798 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
799 // Hide the soft keyboard. `0` indicates no additional flags.
800 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
802 // Consume the event.
804 } else { // A different key was pressed.
805 // Do not consume the event.
810 // Implement swipe to refresh
811 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
812 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
813 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
815 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
816 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
817 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
819 // Listen for touches on the navigation menu.
820 final NavigationView navigationView = findViewById(R.id.navigationview);
821 navigationView.setNavigationItemSelectedListener(this);
823 // 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.
824 final Menu navigationMenu = navigationView.getMenu();
825 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
826 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
827 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
828 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
830 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
831 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
832 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
834 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
835 currentBookmarksFolder = "";
837 // Load the home folder, which is `""` in the database.
838 loadBookmarksFolder();
840 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
841 // Convert the id from long to int to match the format of the bookmarks database.
842 int databaseID = (int) id;
844 // Get the bookmark cursor for this ID and move it to the first row.
845 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
846 bookmarkCursor.moveToFirst();
848 // Act upon the bookmark according to the type.
849 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
850 // Store the new folder name in `currentBookmarksFolder`.
851 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
853 // Load the new folder.
854 loadBookmarksFolder();
855 } else { // The selected bookmark is not a folder.
856 // Load the bookmark URL.
857 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
859 // Close the bookmarks drawer.
860 drawerLayout.closeDrawer(GravityCompat.END);
863 // Close the `Cursor`.
864 bookmarkCursor.close();
867 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
868 // Convert the database ID from `long` to `int`.
869 int databaseId = (int) id;
871 // Find out if the selected bookmark is a folder.
872 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
875 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
876 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
878 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
879 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
880 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
882 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
883 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
884 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
887 // Consume the event.
891 // The drawer listener is used to update the navigation menu.
892 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
894 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
898 public void onDrawerOpened(@NonNull View drawerView) {
902 public void onDrawerClosed(@NonNull View drawerView) {
906 public void onDrawerStateChanged(int newState) {
907 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
908 // Update the back, forward, history, and requests menu items.
909 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
910 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
911 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
912 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
914 // Hide the keyboard (if displayed).
915 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
917 // Clear the focus from from the URL text box.
918 urlTextBox.clearFocus();
923 // drawerToggle creates the hamburger icon at the start of the AppBar.
924 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
926 // Get a handle for the progress bar.
927 final ProgressBar progressBar = findViewById(R.id.progress_bar);
929 mainWebView.setWebChromeClient(new WebChromeClient() {
930 // Update the progress bar when a page is loading.
932 public void onProgressChanged(WebView view, int progress) {
933 // Inject the night mode CSS if night mode is enabled.
935 // `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
936 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
937 // `border: none` removes all borders, which can also be used to underline text.
938 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
939 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
940 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
941 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
942 // Initialize a `Handler` to display `mainWebView`.
943 Handler displayWebViewHandler = new Handler();
945 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
946 Runnable displayWebViewRunnable = () -> {
947 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
948 if (progressBar.getVisibility() == View.GONE) {
949 mainWebView.setVisibility(View.VISIBLE);
953 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
954 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
958 // Update the progress bar.
959 progressBar.setProgress(progress);
961 // Set the visibility of the progress bar.
962 if (progress < 100) {
963 // Show the progress bar.
964 progressBar.setVisibility(View.VISIBLE);
966 // Hide the progress bar.
967 progressBar.setVisibility(View.GONE);
969 // Display `mainWebView` if night mode is disabled.
970 // 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
971 // currently enabled.
973 mainWebView.setVisibility(View.VISIBLE);
976 //Stop the swipe to refresh indicator if it is running
977 swipeRefreshLayout.setRefreshing(false);
981 // Set the favorite icon when it changes.
983 public void onReceivedIcon(WebView view, Bitmap icon) {
984 // Only update the favorite icon if the website has finished loading.
985 if (progressBar.getVisibility() == View.GONE) {
986 // Save a copy of the favorite icon.
987 favoriteIconBitmap = icon;
989 // Place the favorite icon in the appBar.
990 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
994 // Save a copy of the title when it changes.
996 public void onReceivedTitle(WebView view, String title) {
997 // Save a copy of the title.
998 webViewTitle = title;
1001 // Enter full screen video.
1003 public void onShowCustomView(View view, CustomViewCallback callback) {
1004 // Set the full screen video flag.
1005 displayingFullScreenVideo = true;
1007 // Pause the ad if this is the free flavor.
1008 if (BuildConfig.FLAVOR.contentEquals("free")) {
1009 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1010 AdHelper.pauseAd(findViewById(R.id.adview));
1013 // Remove the translucent overlays.
1014 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1016 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1017 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1019 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1020 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1021 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1023 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1025 // Set `rootCoordinatorLayout` to fill the entire screen.
1026 rootCoordinatorLayout.setFitsSystemWindows(false);
1028 // Disable the sliding drawers.
1029 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1031 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1032 fullScreenVideoFrameLayout.addView(view);
1033 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1036 // Exit full screen video.
1038 public void onHideCustomView() {
1039 // Unset the full screen video flag.
1040 displayingFullScreenVideo = true;
1042 // Hide `fullScreenVideoFrameLayout`.
1043 fullScreenVideoFrameLayout.removeAllViews();
1044 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1046 // Enable the sliding drawers.
1047 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1049 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1050 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1051 if (hideSystemBarsOnFullscreen) { // Hide everything.
1052 // Remove the translucent navigation setting if it is currently flagged.
1053 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1055 // Remove the translucent status bar overlay.
1056 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1058 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1059 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1061 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1062 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1063 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1065 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1066 } else { // Hide everything except the status and navigation bars.
1067 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1068 rootCoordinatorLayout.setSystemUiVisibility(0);
1070 // Add the translucent status flag if it is unset.
1071 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1073 if (translucentNavigationBarOnFullscreen) {
1074 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1075 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1077 // Set the navigation bar to be black.
1078 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1081 } else { // Switch to normal viewing mode.
1082 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1083 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1087 // Show the `BannerAd` in the free flavor.
1088 if (BuildConfig.FLAVOR.contentEquals("free")) {
1089 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1090 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1093 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1094 rootCoordinatorLayout.setSystemUiVisibility(0);
1096 // Remove the translucent navigation bar flag if it is set.
1097 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1099 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1100 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1102 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1103 rootCoordinatorLayout.setFitsSystemWindows(true);
1106 // Show the ad if this is the free flavor.
1107 if (BuildConfig.FLAVOR.contentEquals("free")) {
1108 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1109 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1115 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1116 // Show the file chooser if the device is running API >= 21.
1117 if (Build.VERSION.SDK_INT >= 21) {
1118 // Store the file path callback.
1119 fileChooserCallback = filePathCallback;
1121 // Create an intent to open a chooser based ont the file chooser parameters.
1122 Intent fileChooserIntent = fileChooserParams.createIntent();
1124 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1125 startActivityForResult(fileChooserIntent, 0);
1131 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1132 registerForContextMenu(mainWebView);
1134 // Allow the downloading of files.
1135 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1136 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1137 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1138 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1140 // Store the variables for future use by `onRequestPermissionsResult()`.
1142 downloadContentDisposition = contentDisposition;
1143 downloadContentLength = contentLength;
1145 // Show a dialog if the user has previously denied the permission.
1146 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1147 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1148 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1150 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1151 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1152 } else { // Show the permission request directly.
1153 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1154 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1156 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1157 // Get a handle for the download file alert dialog.
1158 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1160 // Show the download file alert dialog.
1161 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1165 // Allow pinch to zoom.
1166 mainWebView.getSettings().setBuiltInZoomControls(true);
1168 // Hide zoom controls.
1169 mainWebView.getSettings().setDisplayZoomControls(false);
1171 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1172 mainWebView.getSettings().setUseWideViewPort(true);
1174 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1175 mainWebView.getSettings().setLoadWithOverviewMode(true);
1177 // Explicitly disable geolocation.
1178 mainWebView.getSettings().setGeolocationEnabled(false);
1180 // Initialize cookieManager.
1181 cookieManager = CookieManager.getInstance();
1183 // 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).
1184 customHeaders.put("X-Requested-With", "");
1186 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1187 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1189 // Get the intent that started the app.
1190 final Intent launchingIntent = getIntent();
1192 // Extract the launching intent data as `launchingIntentUriData`.
1193 final Uri launchingIntentUriData = launchingIntent.getData();
1195 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1196 if (launchingIntentUriData != null) {
1197 formattedUrlString = launchingIntentUriData.toString();
1200 // Get a handle for the `Runtime`.
1201 privacyBrowserRuntime = Runtime.getRuntime();
1203 // Store the application's private data directory.
1204 privateDataDirectoryString = getApplicationInfo().dataDir;
1205 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1207 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1208 inFullScreenBrowsingMode = false;
1210 // Initialize the privacy settings variables.
1211 javaScriptEnabled = false;
1212 firstPartyCookiesEnabled = false;
1213 thirdPartyCookiesEnabled = false;
1214 domStorageEnabled = false;
1215 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1218 // Initialize the WebView title.
1219 webViewTitle = getString(R.string.no_title);
1221 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1222 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1223 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1224 assert favoriteIconBitmapDrawable != null;
1225 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1227 // If the favorite icon is null, load the default.
1228 if (favoriteIconBitmap == null) {
1229 favoriteIconBitmap = favoriteIconDefaultBitmap;
1232 // Initialize the user agent array adapter and string array.
1233 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1234 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1236 // Apply the app settings from the shared preferences.
1239 // Instantiate the block list helper.
1240 BlockListHelper blockListHelper = new BlockListHelper();
1242 // Initialize the list of resource requests.
1243 resourceRequests = new ArrayList<>();
1245 // Parse the block lists.
1246 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1247 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1248 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1249 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1250 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1252 // Store the list versions.
1253 easyListVersion = easyList.get(0).get(0)[0];
1254 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1255 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1256 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1257 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1259 // Get a handle for the activity. This is used to update the requests counter while the navigation menu is open.
1260 Activity activity = this;
1262 mainWebView.setWebViewClient(new WebViewClient() {
1263 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1264 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1265 @SuppressWarnings("deprecation")
1267 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1268 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1269 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1270 formattedUrlString = "";
1272 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1273 applyDomainSettings(url, true, false);
1275 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1277 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1278 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1279 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1281 // Parse the url and set it as the data for the intent.
1282 emailIntent.setData(Uri.parse(url));
1284 // Open the email program in a new task instead of as part of Privacy Browser.
1285 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1288 startActivity(emailIntent);
1290 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1292 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1293 // Open the dialer and load the phone number, but wait for the user to place the call.
1294 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1296 // Add the phone number to the intent.
1297 dialIntent.setData(Uri.parse(url));
1299 // Open the dialer in a new task instead of as part of Privacy Browser.
1300 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1303 startActivity(dialIntent);
1305 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1307 } else { // Load a system chooser to select an app that can handle the URL.
1308 // Open an app that can handle the URL.
1309 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1311 // Add the URL to the intent.
1312 genericIntent.setData(Uri.parse(url));
1314 // List all apps that can handle the URL instead of just opening the first one.
1315 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1317 // Open the app in a new task instead of as part of Privacy Browser.
1318 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1320 // Start the app or display a snackbar if no app is available to handle the URL.
1322 startActivity(genericIntent);
1323 } catch (ActivityNotFoundException exception) {
1324 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1327 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1332 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1333 @SuppressWarnings("deprecation")
1335 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1336 // Create an empty web resource response to be used if the resource request is blocked.
1337 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1339 // Reset the whitelist results tracker.
1340 whiteListResultStringArray = null;
1342 // Initialize the third party request tracker.
1343 boolean isThirdPartyRequest = false;
1345 // Initialize the current domain string.
1346 String currentDomain = "";
1348 // Nobody is happy when comparing null strings.
1349 if (!(formattedUrlString == null) && !(url == null)) {
1350 // Get the domain strings to URIs.
1351 Uri currentDomainUri = Uri.parse(formattedUrlString);
1352 Uri requestDomainUri = Uri.parse(url);
1354 // Get the domain host names.
1355 String currentBaseDomain = currentDomainUri.getHost();
1356 String requestBaseDomain = requestDomainUri.getHost();
1358 // Update the current domain variable.
1359 currentDomain = currentBaseDomain;
1361 // Only compare the current base domain and the request base domain if neither is null.
1362 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1363 // Determine the current base domain.
1364 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1365 // Remove the first subdomain.
1366 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1369 // Determine the request base domain.
1370 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1371 // Remove the first subdomain.
1372 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1375 // Update the third party request tracker.
1376 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1380 // Block third-party requests if enabled.
1381 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1382 // Increment the blocked requests counters.
1384 thirdPartyBlockedRequests++;
1386 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1387 activity.runOnUiThread(() -> {
1388 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1389 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1392 // Add the request to the log.
1393 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1395 // Return an empty web resource response.
1396 return emptyWebResourceResponse;
1399 // Check UltraPrivacy if it is enabled.
1400 if (ultraPrivacyEnabled) {
1401 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1402 // Increment the blocked requests counters.
1404 ultraPrivacyBlockedRequests++;
1406 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1407 activity.runOnUiThread(() -> {
1408 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1409 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1412 // The resource request was blocked. Return an empty web resource response.
1413 return emptyWebResourceResponse;
1416 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1417 if (whiteListResultStringArray != null) {
1418 // Add a whitelist entry to the resource requests array.
1419 resourceRequests.add(whiteListResultStringArray);
1421 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1426 // Check EasyList if it is enabled.
1427 if (easyListEnabled) {
1428 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1429 // Increment the blocked requests counters.
1431 easyListBlockedRequests++;
1433 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1434 activity.runOnUiThread(() -> {
1435 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1436 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1439 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1440 whiteListResultStringArray = null;
1442 // The resource request was blocked. Return an empty web resource response.
1443 return emptyWebResourceResponse;
1447 // Check EasyPrivacy if it is enabled.
1448 if (easyPrivacyEnabled) {
1449 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1450 // Increment the blocked requests counters.
1452 easyPrivacyBlockedRequests++;
1454 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1455 activity.runOnUiThread(() -> {
1456 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1457 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1460 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1461 whiteListResultStringArray = null;
1463 // The resource request was blocked. Return an empty web resource response.
1464 return emptyWebResourceResponse;
1468 // Check Fanboy’s Annoyance List if it is enabled.
1469 if (fanboysAnnoyanceListEnabled) {
1470 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1471 // Increment the blocked requests counters.
1473 fanboysAnnoyanceListBlockedRequests++;
1475 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1476 activity.runOnUiThread(() -> {
1477 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1478 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1481 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1482 whiteListResultStringArray = null;
1484 // The resource request was blocked. Return an empty web resource response.
1485 return emptyWebResourceResponse;
1487 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1488 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1489 // Increment the blocked requests counters.
1491 fanboysSocialBlockingListBlockedRequests++;
1493 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1494 activity.runOnUiThread(() -> {
1495 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1496 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1499 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1500 whiteListResultStringArray = null;
1502 // The resource request was blocked. Return an empty web resource response.
1503 return emptyWebResourceResponse;
1507 // Add the request to the log because it hasn't been processed by any of the previous checks.
1508 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1509 resourceRequests.add(whiteListResultStringArray);
1510 } else { // The request didn't match any blocklist entry. Log it as a defult request.
1511 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1514 // The resource request has not been blocked. `return null` loads the requested resource.
1518 // Handle HTTP authentication requests.
1520 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1521 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1522 httpAuthHandler = handler;
1524 // Display the HTTP authentication dialog.
1525 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1526 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1529 // Update the URL in urlTextBox when the page starts to load.
1531 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1532 // Reset the list of resource requests.
1533 resourceRequests.clear();
1535 // Initialize the counters for requests blocked by each blocklist.
1536 blockedRequests = 0;
1537 easyListBlockedRequests = 0;
1538 easyPrivacyBlockedRequests = 0;
1539 fanboysAnnoyanceListBlockedRequests = 0;
1540 fanboysSocialBlockingListBlockedRequests = 0;
1541 ultraPrivacyBlockedRequests = 0;
1542 thirdPartyBlockedRequests = 0;
1544 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1546 mainWebView.setVisibility(View.INVISIBLE);
1549 // Hide the keyboard. `0` indicates no additional flags.
1550 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1552 // Check to see if Privacy Browser is waiting on Orbot.
1553 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1554 // 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.
1555 formattedUrlString = url;
1557 // Display the formatted URL text.
1558 urlTextBox.setText(formattedUrlString);
1560 // Apply text highlighting to `urlTextBox`.
1563 // Apply any custom domain settings if the URL was loaded by navigating history.
1564 if (navigatingHistory) {
1565 // Reset `navigatingHistory`.
1566 navigatingHistory = false;
1568 // Apply the domain settings.
1569 applyDomainSettings(url, true, false);
1572 // 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.
1573 urlIsLoading = true;
1575 // Replace Refresh with Stop if the menu item has been created. (The WebView typically begins loading before the menu items are instantiated.)
1576 if (refreshMenuItem != null) {
1578 refreshMenuItem.setTitle(R.string.stop);
1580 // If the icon is displayed in the AppBar, set it according to the theme.
1581 if (displayAdditionalAppBarIcons) {
1583 refreshMenuItem.setIcon(R.drawable.close_dark);
1585 refreshMenuItem.setIcon(R.drawable.close_light);
1592 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1594 public void onPageFinished(WebView view, String url) {
1595 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1596 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1597 cookieManager.flush();
1600 // Update the Refresh menu item if it has been created.
1601 if (refreshMenuItem != null) {
1602 // Reset the Refresh title.
1603 refreshMenuItem.setTitle(R.string.refresh);
1605 // If the icon is displayed in the AppBar, reset it according to the theme.
1606 if (displayAdditionalAppBarIcons) {
1608 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1610 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1615 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1616 urlIsLoading = false;
1618 // Clear the cache and history if Incognito Mode is enabled.
1619 if (incognitoModeEnabled) {
1620 // Clear the cache. `true` includes disk files.
1621 mainWebView.clearCache(true);
1623 // Clear the back/forward history.
1624 mainWebView.clearHistory();
1626 // Manually delete cache folders.
1628 // Delete the main cache directory.
1629 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1631 // Delete the secondary `Service Worker` cache directory.
1632 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1633 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1634 } catch (IOException e) {
1635 // Do nothing if an error is thrown.
1639 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1640 if (!waitingForOrbot) {
1641 // Check to see if `WebView` has set `url` to be `about:blank`.
1642 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1643 // Set `formattedUrlString` to `""`.
1644 formattedUrlString = "";
1646 urlTextBox.setText(formattedUrlString);
1648 // Request focus for `urlTextBox`.
1649 urlTextBox.requestFocus();
1651 // Display the keyboard.
1652 inputMethodManager.showSoftInput(urlTextBox, 0);
1654 // Apply the domain settings. This clears any settings from the previous domain.
1655 applyDomainSettings(formattedUrlString, true, false);
1656 } else { // `WebView` has loaded a webpage.
1657 // Set `formattedUrlString`.
1658 formattedUrlString = url;
1660 // Only update `urlTextBox` if the user is not typing in it.
1661 if (!urlTextBox.hasFocus()) {
1662 // Display the formatted URL text.
1663 urlTextBox.setText(formattedUrlString);
1665 // Apply text highlighting to `urlTextBox`.
1670 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1671 sslCertificate = mainWebView.getCertificate();
1673 // 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.
1674 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1675 // Initialize the current SSL certificate variables.
1676 String currentWebsiteIssuedToCName = "";
1677 String currentWebsiteIssuedToOName = "";
1678 String currentWebsiteIssuedToUName = "";
1679 String currentWebsiteIssuedByCName = "";
1680 String currentWebsiteIssuedByOName = "";
1681 String currentWebsiteIssuedByUName = "";
1682 Date currentWebsiteSslStartDate = null;
1683 Date currentWebsiteSslEndDate = null;
1686 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1687 if (sslCertificate != null) {
1688 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1689 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1690 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1691 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1692 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1693 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1694 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1695 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1698 // 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`.
1699 String currentWebsiteSslStartDateString = "";
1700 String currentWebsiteSslEndDateString = "";
1701 String pinnedDomainSslStartDateString = "";
1702 String pinnedDomainSslEndDateString = "";
1704 // Convert the `Dates` to `Strings` if they are not `null`.
1705 if (currentWebsiteSslStartDate != null) {
1706 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1709 if (currentWebsiteSslEndDate != null) {
1710 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1713 if (pinnedDomainSslStartDate != null) {
1714 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1717 if (pinnedDomainSslEndDate != null) {
1718 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1721 // Check to see if the pinned SSL certificate matches the current website certificate.
1722 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1723 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1724 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1725 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1726 // The pinned SSL certificate doesn't match the current domain certificate.
1727 //Display the pinned SSL certificate mismatch `AlertDialog`.
1728 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1729 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1735 // Handle SSL Certificate errors.
1737 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1738 // Get the current website SSL certificate.
1739 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1741 // Extract the individual pieces of information from the current website SSL certificate.
1742 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1743 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1744 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1745 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1746 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1747 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1748 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1749 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1751 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1752 if (pinnedDomainSslCertificate &&
1753 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1754 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1755 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1756 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1757 // An SSL certificate is pinned and matches the current domain certificate.
1758 // Proceed to the website without displaying an error.
1760 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1761 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1762 sslErrorHandler = handler;
1764 // Display the SSL error `AlertDialog`.
1765 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1766 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1771 // Load the website if not waiting for Orbot to connect.
1772 if (!waitingForOrbot) {
1773 loadUrl(formattedUrlString);
1778 protected void onNewIntent(Intent intent) {
1779 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1782 // Check to see if the intent contains a new URL.
1783 if (intent.getData() != null) {
1784 // Get the intent data.
1785 final Uri intentUriData = intent.getData();
1787 // Load the website.
1788 loadUrl(intentUriData.toString());
1790 // Close the navigation drawer if it is open.
1791 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1792 drawerLayout.closeDrawer(GravityCompat.START);
1795 // Close the bookmarks drawer if it is open.
1796 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1797 drawerLayout.closeDrawer(GravityCompat.END);
1800 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1801 mainWebView.requestFocus();
1806 public void onRestart() {
1807 // Run the default commands.
1810 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1811 if (proxyThroughOrbot) {
1812 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1813 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1815 // Send the intent to the Orbot package.
1816 orbotIntent.setPackage("org.torproject.android");
1819 sendBroadcast(orbotIntent);
1822 // Apply the app settings if returning from the Settings activity..
1823 if (reapplyAppSettingsOnRestart) {
1824 // Apply the app settings.
1827 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1828 if (reloadOnRestart) {
1829 // Reload `mainWebView`.
1830 mainWebView.reload();
1832 // Reset `reloadOnRestartBoolean`.
1833 reloadOnRestart = false;
1836 // Reset the return from settings flag.
1837 reapplyAppSettingsOnRestart = false;
1840 // Apply the domain settings if returning from the Domains activity.
1841 if (reapplyDomainSettingsOnRestart) {
1842 // Reapply the domain settings.
1843 applyDomainSettings(formattedUrlString, false, true);
1845 // Reset `reapplyDomainSettingsOnRestart`.
1846 reapplyDomainSettingsOnRestart = false;
1849 // Load the URL on restart to apply changes to night mode.
1850 if (loadUrlOnRestart) {
1851 // Load the current `formattedUrlString`.
1852 loadUrl(formattedUrlString);
1854 // Reset `loadUrlOnRestart.
1855 loadUrlOnRestart = false;
1858 // Update the bookmarks drawer if returning from the Bookmarks activity.
1859 if (restartFromBookmarksActivity) {
1860 // Close the bookmarks drawer.
1861 drawerLayout.closeDrawer(GravityCompat.END);
1863 // Reload the bookmarks drawer.
1864 loadBookmarksFolder();
1866 // Reset `restartFromBookmarksActivity`.
1867 restartFromBookmarksActivity = false;
1870 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1871 updatePrivacyIcons(true);
1874 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1876 public void onResume() {
1877 // Run the default commands.
1880 // Resume JavaScript (if enabled).
1881 mainWebView.resumeTimers();
1883 // Resume `mainWebView`.
1884 mainWebView.onResume();
1886 // Resume the adView for the free flavor.
1887 if (BuildConfig.FLAVOR.contentEquals("free")) {
1889 AdHelper.resumeAd(findViewById(R.id.adview));
1892 // Display a message to the user if waiting for Orbot.
1893 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1894 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1895 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1898 if (displayingFullScreenVideo) {
1899 // Remove the translucent overlays.
1900 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1902 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1903 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1905 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1906 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1907 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1909 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1914 public void onPause() {
1915 // Run the default commands.
1918 // Pause `mainWebView`.
1919 mainWebView.onPause();
1921 // Stop all JavaScript.
1922 mainWebView.pauseTimers();
1924 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1925 if (BuildConfig.FLAVOR.contentEquals("free")) {
1927 AdHelper.pauseAd(findViewById(R.id.adview));
1932 public void onDestroy() {
1933 // Unregister the Orbot status broadcast receiver.
1934 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1936 // Run the default commands.
1941 public boolean onCreateOptionsMenu(Menu menu) {
1942 // Inflate the menu; this adds items to the action bar if it is present.
1943 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1945 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1948 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1949 updatePrivacyIcons(false);
1951 // Get handles for the menu items.
1952 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1953 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1954 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1955 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1956 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1957 refreshMenuItem = menu.findItem(R.id.refresh);
1958 easyListMenuItem = menu.findItem(R.id.easylist);
1959 easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1960 fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1961 fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1962 ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1963 blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1964 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1966 // Only display third-party cookies if API >= 21
1967 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1969 // Only display the form data menu items if the API < 26.
1970 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1971 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1973 // Only show Ad Consent if this is the free flavor.
1974 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1976 // Get the shared preference values.
1977 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1979 // Get the status of the additional AppBar icons.
1980 displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1982 // 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.
1983 if (displayAdditionalAppBarIcons) {
1984 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1985 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1986 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1987 } else { //Do not display the additional icons.
1988 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1989 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1990 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1993 // Update the display names for the blocklists with the number of blocked requests.
1994 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1995 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1996 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1997 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1998 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1999 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
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 font size variables.
2098 int fontSize = mainWebView.getSettings().getTextZoom();
2099 String fontSizeTitle;
2100 MenuItem selectedFontSizeMenuItem;
2102 // Prepare the font size title and current size menu item.
2105 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2106 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2110 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2111 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2115 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2116 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2120 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2121 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2125 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2126 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2130 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2131 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2135 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2136 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2140 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2141 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2145 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2146 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2150 // Set the font size title and select the current size menu item.
2151 fontSizeMenuItem.setTitle(fontSizeTitle);
2152 selectedFontSizeMenuItem.setChecked(true);
2154 // Run all the other default commands.
2155 super.onPrepareOptionsMenu(menu);
2157 // Display the menu.
2162 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2163 @SuppressLint("SetJavaScriptEnabled")
2164 // removeAllCookies is deprecated, but it is required for API < 21.
2165 @SuppressWarnings("deprecation")
2166 public boolean onOptionsItemSelected(MenuItem menuItem) {
2167 // Get the selected menu item ID.
2168 int menuItemId = menuItem.getItemId();
2170 // Set the commands that relate to the menu entries.
2171 switch (menuItemId) {
2172 case R.id.toggle_javascript:
2173 // Switch the status of javaScriptEnabled.
2174 javaScriptEnabled = !javaScriptEnabled;
2176 // Apply the new JavaScript status.
2177 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2179 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2180 updatePrivacyIcons(true);
2182 // Display a `Snackbar`.
2183 if (javaScriptEnabled) { // JavaScrip is enabled.
2184 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2185 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2186 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2187 } else { // Privacy mode.
2188 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2191 // Reload the WebView.
2192 mainWebView.reload();
2195 case R.id.add_or_edit_domain:
2196 if (domainSettingsApplied) { // Edit the current domain settings.
2197 // Reapply the domain settings on returning to `MainWebViewActivity`.
2198 reapplyDomainSettingsOnRestart = true;
2199 currentDomainName = "";
2201 // Create an intent to launch the domains activity.
2202 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2204 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2205 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2206 domainsIntent.putExtra("closeOnBack", true);
2209 startActivity(domainsIntent);
2210 } else { // Add a new domain.
2211 // Apply the new domain settings on returning to `MainWebViewActivity`.
2212 reapplyDomainSettingsOnRestart = true;
2213 currentDomainName = "";
2215 // Get the current domain
2216 Uri currentUri = Uri.parse(formattedUrlString);
2217 String currentDomain = currentUri.getHost();
2219 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2220 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2222 // Create the domain and store the database ID.
2223 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2225 // Create an intent to launch the domains activity.
2226 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2228 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2229 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2230 domainsIntent.putExtra("closeOnBack", true);
2233 startActivity(domainsIntent);
2237 case R.id.toggle_first_party_cookies:
2238 // Switch the status of firstPartyCookiesEnabled.
2239 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2241 // Update the menu checkbox.
2242 menuItem.setChecked(firstPartyCookiesEnabled);
2244 // Apply the new cookie status.
2245 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2247 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2248 updatePrivacyIcons(true);
2250 // Display a `Snackbar`.
2251 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2252 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2253 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2254 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2255 } else { // Privacy mode.
2256 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2259 // Reload the WebView.
2260 mainWebView.reload();
2263 case R.id.toggle_third_party_cookies:
2264 if (Build.VERSION.SDK_INT >= 21) {
2265 // Switch the status of thirdPartyCookiesEnabled.
2266 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2268 // Update the menu checkbox.
2269 menuItem.setChecked(thirdPartyCookiesEnabled);
2271 // Apply the new cookie status.
2272 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2274 // Display a `Snackbar`.
2275 if (thirdPartyCookiesEnabled) {
2276 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2278 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2281 // Reload the WebView.
2282 mainWebView.reload();
2283 } // Else do nothing because SDK < 21.
2286 case R.id.toggle_dom_storage:
2287 // Switch the status of domStorageEnabled.
2288 domStorageEnabled = !domStorageEnabled;
2290 // Update the menu checkbox.
2291 menuItem.setChecked(domStorageEnabled);
2293 // Apply the new DOM Storage status.
2294 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2296 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2297 updatePrivacyIcons(true);
2299 // Display a `Snackbar`.
2300 if (domStorageEnabled) {
2301 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2303 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2306 // Reload the WebView.
2307 mainWebView.reload();
2310 // Form data can be removed once the minimum API >= 26.
2311 case R.id.toggle_save_form_data:
2312 // Switch the status of saveFormDataEnabled.
2313 saveFormDataEnabled = !saveFormDataEnabled;
2315 // Update the menu checkbox.
2316 menuItem.setChecked(saveFormDataEnabled);
2318 // Apply the new form data status.
2319 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2321 // Display a `Snackbar`.
2322 if (saveFormDataEnabled) {
2323 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2325 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2328 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2329 updatePrivacyIcons(true);
2331 // Reload the WebView.
2332 mainWebView.reload();
2335 case R.id.clear_cookies:
2336 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2337 .setAction(R.string.undo, v -> {
2338 // Do nothing because everything will be handled by `onDismissed()` below.
2340 .addCallback(new Snackbar.Callback() {
2342 public void onDismissed(Snackbar snackbar, int event) {
2344 // The user pushed the `Undo` button.
2345 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2349 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2351 // `cookieManager.removeAllCookie()` varies by SDK.
2352 if (Build.VERSION.SDK_INT < 21) {
2353 cookieManager.removeAllCookie();
2355 // `null` indicates no callback.
2356 cookieManager.removeAllCookies(null);
2364 case R.id.clear_dom_storage:
2365 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2366 .setAction(R.string.undo, v -> {
2367 // Do nothing because everything will be handled by `onDismissed()` below.
2369 .addCallback(new Snackbar.Callback() {
2371 public void onDismissed(Snackbar snackbar, int event) {
2373 // The user pushed the `Undo` button.
2374 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2378 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2380 // Delete the DOM Storage.
2381 WebStorage webStorage = WebStorage.getInstance();
2382 webStorage.deleteAllData();
2384 // Manually delete the DOM storage files and directories.
2386 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2387 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2389 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2390 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2391 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2392 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2393 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2394 } catch (IOException e) {
2395 // Do nothing if an error is thrown.
2403 // Form data can be remove once the minimum API >= 26.
2404 case R.id.clear_form_data:
2405 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2406 .setAction(R.string.undo, v -> {
2407 // Do nothing because everything will be handled by `onDismissed()` below.
2409 .addCallback(new Snackbar.Callback() {
2411 public void onDismissed(Snackbar snackbar, int event) {
2413 // The user pushed the `Undo` button.
2414 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2418 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2420 // Delete the form data.
2421 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2422 mainWebViewDatabase.clearFormData();
2429 case R.id.font_size_twenty_five_percent:
2430 mainWebView.getSettings().setTextZoom(25);
2433 case R.id.font_size_fifty_percent:
2434 mainWebView.getSettings().setTextZoom(50);
2437 case R.id.font_size_seventy_five_percent:
2438 mainWebView.getSettings().setTextZoom(75);
2441 case R.id.font_size_one_hundred_percent:
2442 mainWebView.getSettings().setTextZoom(100);
2445 case R.id.font_size_one_hundred_twenty_five_percent:
2446 mainWebView.getSettings().setTextZoom(125);
2449 case R.id.font_size_one_hundred_fifty_percent:
2450 mainWebView.getSettings().setTextZoom(150);
2453 case R.id.font_size_one_hundred_seventy_five_percent:
2454 mainWebView.getSettings().setTextZoom(175);
2457 case R.id.font_size_two_hundred_percent:
2458 mainWebView.getSettings().setTextZoom(200);
2461 case R.id.swipe_to_refresh:
2462 // Toggle swipe to refresh.
2463 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2466 case R.id.display_images:
2467 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2468 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2469 mainWebView.reload();
2470 } else { // Images are not currently loaded automatically.
2471 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2474 // Set `onTheFlyDisplayImagesSet`.
2475 onTheFlyDisplayImagesSet = true;
2478 case R.id.view_source:
2479 // Launch the View Source activity.
2480 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2481 startActivity(viewSourceIntent);
2485 // Toggle the EasyList status.
2486 easyListEnabled = !easyListEnabled;
2488 // Update the menu checkbox.
2489 menuItem.setChecked(easyListEnabled);
2491 // Reload the main WebView.
2492 mainWebView.reload();
2495 case R.id.easyprivacy:
2496 // Toggle the EasyPrivacy status.
2497 easyPrivacyEnabled = !easyPrivacyEnabled;
2499 // Update the menu checkbox.
2500 menuItem.setChecked(easyPrivacyEnabled);
2502 // Reload the main WebView.
2503 mainWebView.reload();
2506 case R.id.fanboys_annoyance_list:
2507 // Toggle Fanboy's Annoyance List status.
2508 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2510 // Update the menu checkbox.
2511 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2513 // Update the staus of Fanboy's Social Blocking List.
2514 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2515 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2517 // Reload the main WebView.
2518 mainWebView.reload();
2521 case R.id.fanboys_social_blocking_list:
2522 // Toggle Fanboy's Social Blocking List status.
2523 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2525 // Update the menu checkbox.
2526 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2528 // Reload the main WebView.
2529 mainWebView.reload();
2532 case R.id.ultraprivacy:
2533 // Toggle the UltraPrivacy status.
2534 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2536 // Update the menu checkbox.
2537 menuItem.setChecked(ultraPrivacyEnabled);
2539 // Reload the main WebView.
2540 mainWebView.reload();
2543 case R.id.block_all_third_party_requests:
2544 //Toggle the third-party requests blocker status.
2545 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2547 // Update the menu checkbox.
2548 menuItem.setChecked(blockAllThirdPartyRequests);
2550 // Reload the main WebView.
2551 mainWebView.reload();
2555 // Setup the share string.
2556 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2558 // Create the share intent.
2559 Intent shareIntent = new Intent();
2560 shareIntent.setAction(Intent.ACTION_SEND);
2561 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2562 shareIntent.setType("text/plain");
2565 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2568 case R.id.find_on_page:
2569 // Hide the URL app bar.
2570 supportAppBar.setVisibility(View.GONE);
2572 // Show the Find on Page `RelativeLayout`.
2573 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2575 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2576 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2577 findOnPageEditText.postDelayed(() -> {
2578 // Set the focus on `findOnPageEditText`.
2579 findOnPageEditText.requestFocus();
2581 // Display the keyboard. `0` sets no input flags.
2582 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2587 // Get a `PrintManager` instance.
2588 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2590 // Convert `mainWebView` to `printDocumentAdapter`.
2591 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2593 // Remove the lint error below that `printManager` might be `null`.
2594 assert printManager != null;
2596 // Print the document. The print attributes are `null`.
2597 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2600 case R.id.add_to_homescreen:
2601 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2602 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2603 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2605 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2609 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2610 // Reload the WebView.
2611 mainWebView.reload();
2612 } else { // The stop button was pushed.
2613 // Stop the loading of the WebView.
2614 mainWebView.stopLoading();
2618 case R.id.ad_consent:
2619 // Display the ad consent dialog.
2620 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2621 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2625 // Don't consume the event.
2626 return super.onOptionsItemSelected(menuItem);
2630 // removeAllCookies is deprecated, but it is required for API < 21.
2631 @SuppressWarnings("deprecation")
2633 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2634 int menuItemId = menuItem.getItemId();
2636 switch (menuItemId) {
2642 if (mainWebView.canGoBack()) {
2643 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2644 formattedUrlString = "";
2646 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2647 navigatingHistory = true;
2649 // Load the previous website in the history.
2650 mainWebView.goBack();
2655 if (mainWebView.canGoForward()) {
2656 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2657 formattedUrlString = "";
2659 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2660 navigatingHistory = true;
2662 // Load the next website in the history.
2663 mainWebView.goForward();
2668 // Get the `WebBackForwardList`.
2669 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2671 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2672 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2673 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2677 // Launch the requests activity.
2678 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2679 startActivity(requestsIntent);
2682 case R.id.downloads:
2683 // Launch the system Download Manager.
2684 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2686 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2687 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2689 startActivity(downloadManagerIntent);
2693 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2694 reapplyDomainSettingsOnRestart = true;
2695 currentDomainName = "";
2697 // Launch the domains activity.
2698 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2699 startActivity(domainsIntent);
2703 // Set the flag to reapply app settings on restart when returning from Settings.
2704 reapplyAppSettingsOnRestart = true;
2706 // Set the flag to reapply the domain settings on restart when returning from Settings.
2707 reapplyDomainSettingsOnRestart = true;
2708 currentDomainName = "";
2710 // Launch the settings activity.
2711 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2712 startActivity(settingsIntent);
2716 // Launch `GuideActivity`.
2717 Intent guideIntent = new Intent(this, GuideActivity.class);
2718 startActivity(guideIntent);
2722 // Launch `AboutActivity`.
2723 Intent aboutIntent = new Intent(this, AboutActivity.class);
2724 startActivity(aboutIntent);
2727 case R.id.clearAndExit:
2728 // Get a handle for `sharedPreferences`. `this` references the current context.
2729 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2731 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2734 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2735 // The command to remove cookies changed slightly in API 21.
2736 if (Build.VERSION.SDK_INT >= 21) {
2737 cookieManager.removeAllCookies(null);
2739 cookieManager.removeAllCookie();
2742 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2744 // We have to use two commands because `Runtime.exec()` does not like `*`.
2745 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2746 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2747 } catch (IOException e) {
2748 // Do nothing if an error is thrown.
2752 // Clear DOM storage.
2753 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2754 // Ask `WebStorage` to clear the DOM storage.
2755 WebStorage webStorage = WebStorage.getInstance();
2756 webStorage.deleteAllData();
2758 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2760 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2761 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2763 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2764 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2765 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2766 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2767 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2768 } catch (IOException e) {
2769 // Do nothing if an error is thrown.
2773 // Clear form data if the API < 26.
2774 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2775 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2776 webViewDatabase.clearFormData();
2778 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2780 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2781 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2782 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2783 } catch (IOException e) {
2784 // Do nothing if an error is thrown.
2789 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2790 // `true` includes disk files.
2791 mainWebView.clearCache(true);
2793 // Manually delete the cache directories.
2795 // Delete the main cache directory.
2796 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2798 // Delete the secondary `Service Worker` cache directory.
2799 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2800 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2801 } catch (IOException e) {
2802 // Do nothing if an error is thrown.
2806 // Clear SSL certificate preferences.
2807 mainWebView.clearSslPreferences();
2809 // Clear the back/forward history.
2810 mainWebView.clearHistory();
2812 // Clear `formattedUrlString`.
2813 formattedUrlString = null;
2815 // Clear `customHeaders`.
2816 customHeaders.clear();
2818 // Detach all views from `mainWebViewRelativeLayout`.
2819 mainWebViewRelativeLayout.removeAllViews();
2821 // Destroy the internal state of `mainWebView`.
2822 mainWebView.destroy();
2824 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2825 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2826 if (clearEverything) {
2828 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2829 } catch (IOException e) {
2830 // Do nothing if an error is thrown.
2834 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2835 if (Build.VERSION.SDK_INT >= 21) {
2836 finishAndRemoveTask();
2841 // Remove the terminated program from RAM. The status code is `0`.
2846 // Close the navigation drawer.
2847 drawerLayout.closeDrawer(GravityCompat.START);
2852 public void onPostCreate(Bundle savedInstanceState) {
2853 super.onPostCreate(savedInstanceState);
2855 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2856 drawerToggle.syncState();
2860 public void onConfigurationChanged(Configuration newConfig) {
2861 super.onConfigurationChanged(newConfig);
2863 // Reload the ad for the free flavor if we not in full screen mode.
2864 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2865 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2866 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2869 // `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:
2870 // https://code.google.com/p/android/issues/detail?id=20493#c8
2871 // ActivityCompat.invalidateOptionsMenu(this);
2875 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2876 // Store the `HitTestResult`.
2877 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2880 final String imageUrl;
2881 final String linkUrl;
2883 // Get a handle for the `ClipboardManager`.
2884 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2886 // Remove the lint errors below that `clipboardManager` might be `null`.
2887 assert clipboardManager != null;
2889 switch (hitTestResult.getType()) {
2890 // `SRC_ANCHOR_TYPE` is a link.
2891 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2892 // Get the target URL.
2893 linkUrl = hitTestResult.getExtra();
2895 // Set the target URL as the title of the `ContextMenu`.
2896 menu.setHeaderTitle(linkUrl);
2898 // Add a Load URL entry.
2899 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2904 // Add a Copy URL entry.
2905 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2906 // Save the link URL in a `ClipData`.
2907 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2909 // Set the `ClipData` as the clipboard's primary clip.
2910 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2914 // Add a Download URL entry.
2915 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2916 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2917 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2918 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2920 // Store the variables for future use by `onRequestPermissionsResult()`.
2921 downloadUrl = linkUrl;
2922 downloadContentDisposition = "none";
2923 downloadContentLength = -1;
2925 // Show a dialog if the user has previously denied the permission.
2926 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2927 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2928 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2930 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2931 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2932 } else { // Show the permission request directly.
2933 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2934 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2936 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2937 // Get a handle for the download file alert dialog.
2938 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2940 // Show the download file alert dialog.
2941 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2946 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2947 menu.add(R.string.cancel);
2950 case WebView.HitTestResult.EMAIL_TYPE:
2951 // Get the target URL.
2952 linkUrl = hitTestResult.getExtra();
2954 // Set the target URL as the title of the `ContextMenu`.
2955 menu.setHeaderTitle(linkUrl);
2957 // Add a `Write Email` entry.
2958 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2959 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2960 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2962 // Parse the url and set it as the data for the `Intent`.
2963 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2965 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2966 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2969 startActivity(emailIntent);
2973 // Add a `Copy Email Address` entry.
2974 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2975 // Save the email address in a `ClipData`.
2976 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2978 // Set the `ClipData` as the clipboard's primary clip.
2979 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2983 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2984 menu.add(R.string.cancel);
2987 // `IMAGE_TYPE` is an image.
2988 case WebView.HitTestResult.IMAGE_TYPE:
2989 // Get the image URL.
2990 imageUrl = hitTestResult.getExtra();
2992 // Set the image URL as the title of the `ContextMenu`.
2993 menu.setHeaderTitle(imageUrl);
2995 // Add a `View Image` entry.
2996 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3001 // Add a `Download Image` entry.
3002 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3003 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3004 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3005 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3007 // Store the image URL for use by `onRequestPermissionResult()`.
3008 downloadImageUrl = imageUrl;
3010 // Show a dialog if the user has previously denied the permission.
3011 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3012 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3013 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3015 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3016 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3017 } else { // Show the permission request directly.
3018 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3019 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3021 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3022 // Get a handle for the download image alert dialog.
3023 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3025 // Show the download image alert dialog.
3026 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3031 // Add a `Copy URL` entry.
3032 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3033 // Save the image URL in a `ClipData`.
3034 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3036 // Set the `ClipData` as the clipboard's primary clip.
3037 clipboardManager.setPrimaryClip(srcImageTypeClipData);
3041 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3042 menu.add(R.string.cancel);
3046 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
3047 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
3048 // Get the image URL.
3049 imageUrl = hitTestResult.getExtra();
3051 // Set the image URL as the title of the `ContextMenu`.
3052 menu.setHeaderTitle(imageUrl);
3054 // Add a `View Image` entry.
3055 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3060 // Add a `Download Image` entry.
3061 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3062 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3063 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3064 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3066 // Store the image URL for use by `onRequestPermissionResult()`.
3067 downloadImageUrl = imageUrl;
3069 // Show a dialog if the user has previously denied the permission.
3070 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3071 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3072 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3074 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3075 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3076 } else { // Show the permission request directly.
3077 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3078 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3080 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3081 // Get a handle for the download image alert dialog.
3082 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3084 // Show the download image alert dialog.
3085 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3090 // Add a `Copy URL` entry.
3091 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3092 // Save the image URL in a `ClipData`.
3093 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3095 // Set the `ClipData` as the clipboard's primary clip.
3096 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3100 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3101 menu.add(R.string.cancel);
3107 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3108 // Get the `EditTexts` from the `dialogFragment`.
3109 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3110 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3112 // Extract the strings from the `EditTexts`.
3113 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3114 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3116 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3117 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3118 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3119 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3121 // Display the new bookmark below the current items in the (0 indexed) list.
3122 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3124 // Create the bookmark.
3125 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3127 // Update `bookmarksCursor` with the current contents of this folder.
3128 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3130 // Update the `ListView`.
3131 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3133 // Scroll to the new bookmark.
3134 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3138 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3139 // Get handles for the views in `dialogFragment`.
3140 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3141 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3142 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3144 // Get new folder name string.
3145 String folderNameString = createFolderNameEditText.getText().toString();
3147 // Get the new folder icon `Bitmap`.
3148 Bitmap folderIconBitmap;
3149 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3150 // Get the default folder icon and convert it to a `Bitmap`.
3151 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3152 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3153 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3154 } else { // Use the `WebView` favorite icon.
3155 folderIconBitmap = favoriteIconBitmap;
3158 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3159 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3160 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3161 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3163 // Move all the bookmarks down one in the display order.
3164 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3165 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3166 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3169 // Create the folder, which will be placed at the top of the `ListView`.
3170 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3172 // Update `bookmarksCursor` with the current contents of this folder.
3173 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3175 // Update the `ListView`.
3176 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3178 // Scroll to the new folder.
3179 bookmarksListView.setSelection(0);
3183 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3184 // Get the shortcut name.
3185 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3186 String shortcutNameString = shortcutNameEditText.getText().toString();
3188 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3189 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3191 // Setup the shortcut intent.
3192 Intent shortcutIntent = new Intent();
3193 shortcutIntent.setAction(Intent.ACTION_VIEW);
3194 shortcutIntent.setData(Uri.parse(formattedUrlString));
3196 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3197 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3199 // Add the required fields to the shortcut info builder.
3200 shortcutInfoBuilder.setIcon(favoriteIcon);
3201 shortcutInfoBuilder.setIntent(shortcutIntent);
3202 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3204 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3205 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3209 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3210 switch (downloadType) {
3211 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3212 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3213 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3216 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3217 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3218 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3224 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
3225 switch (requestCode) {
3226 case DOWNLOAD_FILE_REQUEST_CODE:
3227 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3228 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3230 // On API 23, displaying the fragment must be delayed or the app will crash.
3231 if (Build.VERSION.SDK_INT == 23) {
3232 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3234 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3237 // Reset the download variables.
3239 downloadContentDisposition = "";
3240 downloadContentLength = 0;
3243 case DOWNLOAD_IMAGE_REQUEST_CODE:
3244 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3245 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3247 // On API 23, displaying the fragment must be delayed or the app will crash.
3248 if (Build.VERSION.SDK_INT == 23) {
3249 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3251 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3254 // Reset the image URL variable.
3255 downloadImageUrl = "";
3261 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3262 // Download the image if it has an HTTP or HTTPS URI.
3263 if (imageUrl.startsWith("http")) {
3264 // Get a handle for the system `DOWNLOAD_SERVICE`.
3265 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3267 // Parse `imageUrl`.
3268 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3270 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3271 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3272 if (firstPartyCookiesEnabled) {
3273 // Get the cookies for `imageUrl`.
3274 String cookies = cookieManager.getCookie(imageUrl);
3276 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3277 downloadRequest.addRequestHeader("Cookie", cookies);
3280 // Get the file name from the dialog fragment.
3281 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3282 String imageName = downloadImageNameEditText.getText().toString();
3284 // Specify the download location.
3285 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3286 // Download to the public download directory.
3287 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3288 } else { // External write permission denied.
3289 // Download to the app's external download directory.
3290 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3293 // Allow `MediaScanner` to index the download if it is a media file.
3294 downloadRequest.allowScanningByMediaScanner();
3296 // Add the URL as the description for the download.
3297 downloadRequest.setDescription(imageUrl);
3299 // Show the download notification after the download is completed.
3300 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3302 // Remove the lint warning below that `downloadManager` might be `null`.
3303 assert downloadManager != null;
3305 // Initiate the download.
3306 downloadManager.enqueue(downloadRequest);
3307 } else { // The image is not an HTTP or HTTPS URI.
3308 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3313 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3314 // Download the file if it has an HTTP or HTTPS URI.
3315 if (downloadUrl.startsWith("http")) {
3316 // Get a handle for the system `DOWNLOAD_SERVICE`.
3317 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3319 // Parse `downloadUrl`.
3320 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3322 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3323 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3324 if (firstPartyCookiesEnabled) {
3325 // Get the cookies for `downloadUrl`.
3326 String cookies = cookieManager.getCookie(downloadUrl);
3328 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3329 downloadRequest.addRequestHeader("Cookie", cookies);
3332 // Get the file name from the dialog fragment.
3333 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3334 String fileName = downloadFileNameEditText.getText().toString();
3336 // Specify the download location.
3337 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3338 // Download to the public download directory.
3339 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3340 } else { // External write permission denied.
3341 // Download to the app's external download directory.
3342 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3345 // Allow `MediaScanner` to index the download if it is a media file.
3346 downloadRequest.allowScanningByMediaScanner();
3348 // Add the URL as the description for the download.
3349 downloadRequest.setDescription(downloadUrl);
3351 // Show the download notification after the download is completed.
3352 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3354 // Remove the lint warning below that `downloadManager` might be `null`.
3355 assert downloadManager != null;
3357 // Initiate the download.
3358 downloadManager.enqueue(downloadRequest);
3359 } else { // The download is not an HTTP or HTTPS URI.
3360 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3365 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3366 // Get handles for the views from `dialogFragment`.
3367 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3368 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3369 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3371 // Store the bookmark strings.
3372 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3373 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3375 // Update the bookmark.
3376 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3377 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3378 } else { // Update the bookmark using the `WebView` favorite icon.
3379 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3380 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3381 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3382 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3384 // Update the bookmark and the favorite icon.
3385 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3388 // Update `bookmarksCursor` with the current contents of this folder.
3389 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3391 // Update the `ListView`.
3392 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3396 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3397 // Get handles for the views from `dialogFragment`.
3398 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3399 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3400 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3401 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3403 // Get the new folder name.
3404 String newFolderNameString = editFolderNameEditText.getText().toString();
3406 // Check if the favorite icon has changed.
3407 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3408 // Update the name in the database.
3409 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3410 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3411 // Get the new folder icon `Bitmap`.
3412 Bitmap folderIconBitmap;
3413 if (defaultFolderIconRadioButton.isChecked()) {
3414 // Get the default folder icon and convert it to a `Bitmap`.
3415 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3416 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3417 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3418 } else { // Use the `WebView` favorite icon.
3419 folderIconBitmap = favoriteIconBitmap;
3422 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3423 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3424 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3425 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3427 // Update the folder icon in the database.
3428 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3429 } else { // The folder icon and the name have changed.
3430 // Get the new folder icon `Bitmap`.
3431 Bitmap folderIconBitmap;
3432 if (defaultFolderIconRadioButton.isChecked()) {
3433 // Get the default folder icon and convert it to a `Bitmap`.
3434 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3435 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3436 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3437 } else { // Use the `WebView` favorite icon.
3438 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3441 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3442 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3443 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3444 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3446 // Update the folder name and icon in the database.
3447 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3450 // Update `bookmarksCursor` with the current contents of this folder.
3451 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3453 // Update the `ListView`.
3454 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3458 public void onHttpAuthenticationCancel() {
3459 // Cancel the `HttpAuthHandler`.
3460 httpAuthHandler.cancel();
3464 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3465 // Get handles for the `EditTexts`.
3466 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3467 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3469 // Proceed with the HTTP authentication.
3470 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3473 public void viewSslCertificate(View view) {
3474 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3475 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3476 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3480 public void onSslErrorCancel() {
3481 sslErrorHandler.cancel();
3485 public void onSslErrorProceed() {
3486 sslErrorHandler.proceed();
3490 public void onSslMismatchBack() {
3491 if (mainWebView.canGoBack()) { // There is a back page in the history.
3492 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3493 formattedUrlString = "";
3495 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3496 navigatingHistory = true;
3499 mainWebView.goBack();
3500 } else { // There are no pages to go back to.
3501 // Load a blank page
3507 public void onSslMismatchProceed() {
3508 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3509 ignorePinnedSslCertificate = true;
3513 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3514 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3515 formattedUrlString = "";
3517 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3518 navigatingHistory = true;
3520 // Load the history entry.
3521 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3525 public void onClearHistory() {
3526 // Clear the history.
3527 mainWebView.clearHistory();
3530 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3532 public void onBackPressed() {
3533 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3534 // Close the navigation drawer.
3535 drawerLayout.closeDrawer(GravityCompat.START);
3536 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3537 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3538 // close the bookmarks drawer.
3539 drawerLayout.closeDrawer(GravityCompat.END);
3540 } else { // A subfolder is displayed.
3541 // Place the former parent folder in `currentFolder`.
3542 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3544 // Load the new folder.
3545 loadBookmarksFolder();
3548 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3549 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3550 formattedUrlString = "";
3552 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3553 navigatingHistory = true;
3556 mainWebView.goBack();
3557 } else { // There isn't anything to do in Privacy Browser.
3558 // Pass `onBackPressed()` to the system.
3559 super.onBackPressed();
3563 // Process the results of an upload file chooser. Currently there is only one `startActivityForResult` in this activity, so the request code, used to differentiate them, is ignored.
3565 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3566 // File uploads only work on API >= 21.
3567 if (Build.VERSION.SDK_INT >= 21) {
3568 // Pass the file to the WebView.
3569 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3573 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3574 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3575 String unformattedUrlString = urlTextBox.getText().toString().trim();
3577 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3578 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3579 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3580 if (!unformattedUrlString.startsWith("http")) {
3581 unformattedUrlString = "http://" + unformattedUrlString;
3584 // Initialize `unformattedUrl`.
3585 URL unformattedUrl = null;
3587 // Convert `unformattedUrlString` to a `URL`, then to a `URI`, and then back to a `String`, which sanitizes the input and adds in any missing components.
3589 unformattedUrl = new URL(unformattedUrlString);
3590 } catch (MalformedURLException e) {
3591 e.printStackTrace();
3594 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3595 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3596 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3597 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3598 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3599 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3602 Uri.Builder formattedUri = new Uri.Builder();
3603 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3605 // Decode `formattedUri` as a `String` in `UTF-8`.
3606 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3607 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3608 // Load a blank string.
3609 formattedUrlString = "";
3610 } else { // Search for the contents of the URL box.
3611 // Sanitize the search input and convert it to a search.
3612 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3614 // Add the base search URL.
3615 formattedUrlString = searchURL + encodedUrlString;
3618 // Clear the focus from the URL text box. Otherwise, proximate typing in the box will retain the colorized formatting instead of being reset during refocus.
3619 urlTextBox.clearFocus();
3622 loadUrl(formattedUrlString);
3625 private void loadUrl(String url) {// Apply any custom domain settings.
3626 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3627 formattedUrlString = url;
3629 // Apply the domain settings.
3630 applyDomainSettings(url, true, false);
3632 // If loading a website, set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3633 urlIsLoading = !url.equals("");
3636 mainWebView.loadUrl(url, customHeaders);
3639 public void findPreviousOnPage(View view) {
3640 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3641 mainWebView.findNext(false);
3644 public void findNextOnPage(View view) {
3645 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3646 mainWebView.findNext(true);
3649 public void closeFindOnPage(View view) {
3650 // Delete the contents of `find_on_page_edittext`.
3651 findOnPageEditText.setText(null);
3653 // Clear the highlighted phrases.
3654 mainWebView.clearMatches();
3656 // Hide the Find on Page `RelativeLayout`.
3657 findOnPageLinearLayout.setVisibility(View.GONE);
3659 // Show the URL app bar.
3660 supportAppBar.setVisibility(View.VISIBLE);
3662 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3663 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3666 private void applyAppSettings() {
3667 // Get a handle for the shared preferences.
3668 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3670 // Store the values from the shared preferences in variables.
3671 String homepageString = sharedPreferences.getString("homepage", "https://searx.me/");
3672 String torHomepageString = sharedPreferences.getString("tor_homepage", "http://ulrn6sryqaifefld.onion/");
3673 String torSearchString = sharedPreferences.getString("tor_search", "http://ulrn6sryqaifefld.onion/?q=");
3674 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3675 String searchString = sharedPreferences.getString("search", "https://searx.me/?q=");
3676 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3677 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3678 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3679 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3680 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3681 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3682 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3683 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3685 // Set the homepage, search, and proxy options.
3686 if (proxyThroughOrbot) { // Set the Tor options.
3687 // Set `torHomepageString` as `homepage`.
3688 homepage = torHomepageString;
3690 // If formattedUrlString is null assign the homepage to it.
3691 if (formattedUrlString == null) {
3692 formattedUrlString = homepage;
3695 // Set the search URL.
3696 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3697 searchURL = torSearchCustomURLString;
3698 } else { // Use the string from the pre-built list.
3699 searchURL = torSearchString;
3702 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3703 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3705 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3707 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3709 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3712 // Display a message to the user if waiting for Orbot.
3713 if (!orbotStatus.equals("ON")) {
3714 // Set `waitingForOrbot`.
3715 waitingForOrbot = true;
3717 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3718 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3720 } else { // Set the non-Tor options.
3721 // Set `homepageString` as `homepage`.
3722 homepage = homepageString;
3724 // If formattedUrlString is null assign the homepage to it.
3725 if (formattedUrlString == null) {
3726 formattedUrlString = homepage;
3729 // Set the search URL.
3730 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3731 searchURL = searchCustomURLString;
3732 } else { // Use the string from the pre-built list.
3733 searchURL = searchString;
3736 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3737 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3739 // Set the default `appBar` background. `this` refers to the context.
3741 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3743 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3746 // Reset `waitingForOrbot.
3747 waitingForOrbot = false;
3750 // Set Do Not Track status.
3751 if (doNotTrackEnabled) {
3752 customHeaders.put("DNT", "1");
3754 customHeaders.remove("DNT");
3757 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3758 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3759 if (hideSystemBarsOnFullscreen) { // Hide everything.
3760 // Remove the translucent navigation setting if it is currently flagged.
3761 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3763 // Remove the translucent status bar overlay.
3764 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3766 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3767 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3769 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3770 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3771 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3773 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3774 } else { // Hide everything except the status and navigation bars.
3775 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3776 rootCoordinatorLayout.setSystemUiVisibility(0);
3778 // Add the translucent status flag if it is unset.
3779 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3781 if (translucentNavigationBarOnFullscreen) {
3782 // Set the navigation bar to be translucent.
3783 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3785 // Set the navigation bar to be black.
3786 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3789 } else { // Privacy Browser is not in full screen browsing mode.
3790 // Reset the full screen tracker, which could be true if Privacy Browser was in full screen mode before entering settings and full screen browsing was disabled.
3791 inFullScreenBrowsingMode = false;
3793 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3794 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3798 // Show the `BannerAd` in the free flavor.
3799 if (BuildConfig.FLAVOR.contentEquals("free")) {
3800 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3801 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3804 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3805 rootCoordinatorLayout.setSystemUiVisibility(0);
3807 // Remove the translucent navigation bar flag if it is set.
3808 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3810 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3811 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3813 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3814 rootCoordinatorLayout.setFitsSystemWindows(true);
3818 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3819 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3820 @SuppressWarnings("deprecation")
3821 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3822 // Parse the URL into a URI.
3823 Uri uri = Uri.parse(url);
3825 // Extract the domain from `uri`.
3826 String hostName = uri.getHost();
3828 // Initialize `loadingNewDomainName`.
3829 boolean loadingNewDomainName;
3831 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3832 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3833 //noinspection SimplifiableIfStatement
3834 if ((hostName == null) || (currentDomainName == null)) {
3835 loadingNewDomainName = true;
3836 } else { // Determine if `hostName` equals `currentDomainName`.
3837 loadingNewDomainName = !hostName.equals(currentDomainName);
3840 // Strings don't like to be null.
3841 if (hostName == null) {
3845 // Only apply the domain settings if a new domain is being loaded. This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3846 if (loadingNewDomainName) {
3847 // Set the new `hostname` as the `currentDomainName`.
3848 currentDomainName = hostName;
3850 // Reset `ignorePinnedSslCertificate`.
3851 ignorePinnedSslCertificate = false;
3853 // Reset the favorite icon if specified.
3854 if (resetFavoriteIcon) {
3855 favoriteIconBitmap = favoriteIconDefaultBitmap;
3856 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3859 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3860 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3861 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3863 // Get a full cursor from `domainsDatabaseHelper`.
3864 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3866 // Initialize `domainSettingsSet`.
3867 Set<String> domainSettingsSet = new HashSet<>();
3869 // Get the domain name column index.
3870 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3872 // Populate `domainSettingsSet`.
3873 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3874 // Move `domainsCursor` to the current row.
3875 domainNameCursor.moveToPosition(i);
3877 // Store the domain name in `domainSettingsSet`.
3878 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3881 // Close `domainNameCursor.
3882 domainNameCursor.close();
3884 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3885 domainSettingsApplied = false;
3886 String domainNameInDatabase = null;
3888 // Check the hostname.
3889 if (domainSettingsSet.contains(hostName)) {
3890 domainSettingsApplied = true;
3891 domainNameInDatabase = hostName;
3894 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3895 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3896 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3897 // Apply the domain settings.
3898 domainSettingsApplied = true;
3900 // Store the applied domain names as it appears in the database.
3901 domainNameInDatabase = "*." + hostName;
3904 // Strip out the lowest subdomain of of the host name.
3905 hostName = hostName.substring(hostName.indexOf(".") + 1);
3909 // Get a handle for the shared preference.
3910 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3912 // Store the general preference information.
3913 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3914 String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3915 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3916 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3917 nightMode = sharedPreferences.getBoolean("night_mode", false);
3919 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3920 // Get a cursor for the current host and move it to the first position.
3921 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3922 currentHostDomainSettingsCursor.moveToFirst();
3924 // Get the settings from the cursor.
3925 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3926 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3927 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3928 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3929 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3930 // Form data can be removed once the minimum API >= 26.
3931 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3932 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3933 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3934 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3935 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3936 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3937 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3938 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3939 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3940 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3941 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3942 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3943 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3944 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3945 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3946 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3947 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3948 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3949 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3951 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3952 switch (nightModeInt) {
3953 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3957 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3962 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3964 javaScriptEnabled = true;
3967 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3968 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3969 pinnedDomainSslStartDate = null;
3971 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3974 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3975 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3976 pinnedDomainSslEndDate = null;
3978 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3981 // Close `currentHostDomainSettingsCursor`.
3982 currentHostDomainSettingsCursor.close();
3984 // Apply the domain settings.
3985 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3986 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3987 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3989 // Apply the form data setting if the API < 26.
3990 if (Build.VERSION.SDK_INT < 26) {
3991 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3994 // Apply the font size.
3995 if (fontSize == 0) { // Apply the default font size.
3996 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3997 } else { // Apply the specified font size.
3998 mainWebView.getSettings().setTextZoom(fontSize);
4001 // Set third-party cookies status if API >= 21.
4002 if (Build.VERSION.SDK_INT >= 21) {
4003 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4006 // Only set the user agent if the webpage is not currently loading. Otherwise, changing the user agent on redirects can cause the original website to reload.
4007 // <https://redmine.stoutner.com/issues/160>
4008 if (!urlIsLoading) {
4009 // Set the user agent.
4010 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4011 // Get the array position of the default user agent name.
4012 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4014 // Set the user agent according to the system default.
4015 switch (defaultUserAgentArrayPosition) {
4016 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4017 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4018 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4021 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4022 // Set the user agent to `""`, which uses the default value.
4023 mainWebView.getSettings().setUserAgentString("");
4026 case SETTINGS_CUSTOM_USER_AGENT:
4027 // Set the custom user agent.
4028 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4032 // Get the user agent string from the user agent data array
4033 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4035 } else { // Set the user agent according to the stored name.
4036 // Get the array position of the user agent name.
4037 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4039 switch (userAgentArrayPosition) {
4040 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4041 mainWebView.getSettings().setUserAgentString(userAgentName);
4044 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4045 // Set the user agent to `""`, which uses the default value.
4046 mainWebView.getSettings().setUserAgentString("");
4050 // Get the user agent string from the user agent data array.
4051 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4055 // Set swipe to refresh.
4056 switch (swipeToRefreshInt) {
4057 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
4058 // Set swipe to refresh according to the default.
4059 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4062 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
4063 // Enable swipe to refresh.
4064 swipeRefreshLayout.setEnabled(true);
4067 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
4068 // Disable swipe to refresh.
4069 swipeRefreshLayout.setEnabled(false);
4072 // Store the applied user agent string, which is used in the View Source activity.
4073 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4076 // Set a green background on `urlTextBox` to indicate that custom domain settings are being used. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4078 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4080 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4082 } else { // The new URL does not have custom domain settings. Load the defaults.
4083 // Store the values from `sharedPreferences` in variables.
4084 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
4085 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
4086 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
4087 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
4088 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false); // Form data can be removed once the minimum API >= 26.
4089 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
4090 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
4091 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
4092 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
4093 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
4094 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
4096 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4098 javaScriptEnabled = true;
4101 // Apply the default settings.
4102 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4103 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4104 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4105 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4106 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4108 // Apply the form data setting if the API < 26.
4109 if (Build.VERSION.SDK_INT < 26) {
4110 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4113 // Reset the pinned SSL certificate information.
4114 domainSettingsDatabaseId = -1;
4115 pinnedDomainSslCertificate = false;
4116 pinnedDomainSslIssuedToCNameString = "";
4117 pinnedDomainSslIssuedToONameString = "";
4118 pinnedDomainSslIssuedToUNameString = "";
4119 pinnedDomainSslIssuedByCNameString = "";
4120 pinnedDomainSslIssuedByONameString = "";
4121 pinnedDomainSslIssuedByUNameString = "";
4122 pinnedDomainSslStartDate = null;
4123 pinnedDomainSslEndDate = null;
4125 // Set third-party cookies status if API >= 21.
4126 if (Build.VERSION.SDK_INT >= 21) {
4127 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4130 // Only set the user agent if the webpage is not currently loading. Otherwise, changing the user agent on redirects can cause the original website to reload.
4131 // <https://redmine.stoutner.com/issues/160>
4132 if (!urlIsLoading) {
4133 // Get the array position of the user agent name.
4134 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4136 // Set the user agent.
4137 switch (userAgentArrayPosition) {
4138 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4139 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4140 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4143 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4144 // Set the user agent to `""`, which uses the default value.
4145 mainWebView.getSettings().setUserAgentString("");
4148 case SETTINGS_CUSTOM_USER_AGENT:
4149 // Set the custom user agent.
4150 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4154 // Get the user agent string from the user agent data array
4155 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4158 // Store the applied user agent string, which is used in the View Source activity.
4159 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4162 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4163 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4166 // Close `domainsDatabaseHelper`.
4167 domainsDatabaseHelper.close();
4169 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
4170 onTheFlyDisplayImagesSet = false;
4171 setDisplayWebpageImages();
4173 // Update the privacy icons, but only if `mainMenu` has already been populated.
4174 if (mainMenu != null) {
4175 updatePrivacyIcons(true);
4179 // Reload the website if returning from the Domains activity.
4180 if (reloadWebsite) {
4181 mainWebView.reload();
4185 private void setDisplayWebpageImages() {
4186 if (!onTheFlyDisplayImagesSet) {
4187 if (domainSettingsApplied) { // Custom domain settings are applied.
4188 switch (displayWebpageImagesInt) {
4189 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4190 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4193 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4194 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4197 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4198 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4201 } else { // Default settings are applied.
4202 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4207 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4208 // Get handles for the menu items.
4209 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4210 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4211 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4212 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4214 // Update the privacy icon.
4215 if (javaScriptEnabled) { // JavaScript is enabled.
4216 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4217 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4218 privacyMenuItem.setIcon(R.drawable.warning);
4219 } else { // All the dangerous features are disabled.
4220 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4223 // Update the first-party cookies icon.
4224 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4225 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4226 } else { // First-party cookies are disabled.
4228 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4230 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4234 // Update the DOM storage icon.
4235 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4236 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4237 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4239 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4241 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4243 } else { // JavaScript is disabled, so DOM storage is ghosted.
4245 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4247 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4251 // Update the refresh icon.
4253 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4255 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4258 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4259 if (runInvalidateOptionsMenu) {
4260 invalidateOptionsMenu();
4264 private void highlightUrlText() {
4265 String urlString = urlTextBox.getText().toString();
4267 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4268 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4269 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4270 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4273 // Get the index of the `/` immediately after the domain name.
4274 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4276 // De-emphasize the text after the domain name.
4277 if (endOfDomainName > 0) {
4278 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4282 private void loadBookmarksFolder() {
4283 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4284 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4286 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4287 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4289 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4290 // Inflate the individual item layout. `false` does not attach it to the root.
4291 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4295 public void bindView(View view, Context context, Cursor cursor) {
4296 // Get handles for the views.
4297 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4298 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4300 // Get the favorite icon byte array from the cursor.
4301 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4303 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4304 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4306 // Display the bitmap in `bookmarkFavoriteIcon`.
4307 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4309 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4310 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4311 bookmarkNameTextView.setText(bookmarkNameString);
4313 // Make the font bold for folders.
4314 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4315 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4316 } else { // Reset the font to default for normal bookmarks.
4317 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4322 // Populate the `ListView` with the adapter.
4323 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4325 // Set the bookmarks drawer title.
4326 if (currentBookmarksFolder.isEmpty()) {
4327 bookmarksTitleTextView.setText(R.string.bookmarks);
4329 bookmarksTitleTextView.setText(currentBookmarksFolder);