2 * Copyright © 2015-2018 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.DialogFragment;
28 import android.app.DownloadManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.Environment;
51 import android.os.Handler;
52 import android.preference.PreferenceManager;
53 import android.print.PrintDocumentAdapter;
54 import android.print.PrintManager;
55 import android.support.annotation.NonNull;
56 import android.support.design.widget.CoordinatorLayout;
57 import android.support.design.widget.FloatingActionButton;
58 import android.support.design.widget.NavigationView;
59 import android.support.design.widget.Snackbar;
60 import android.support.v4.app.ActivityCompat;
61 import android.support.v4.content.ContextCompat;
62 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
63 import android.support.v4.content.pm.ShortcutInfoCompat;
64 import android.support.v4.content.pm.ShortcutManagerCompat;
65 import android.support.v4.graphics.drawable.IconCompat;
66 import android.support.v4.view.GravityCompat;
67 import android.support.v4.widget.DrawerLayout;
68 import android.support.v4.widget.SwipeRefreshLayout;
69 import android.support.v7.app.ActionBar;
70 import android.support.v7.app.ActionBarDrawerToggle;
71 import android.support.v7.app.AppCompatActivity;
72 import android.support.v7.app.AppCompatDialogFragment;
73 import android.support.v7.widget.Toolbar;
74 import android.text.Editable;
75 import android.text.Spanned;
76 import android.text.TextWatcher;
77 import android.text.style.ForegroundColorSpan;
78 import android.util.Patterns;
79 import android.view.ContextMenu;
80 import android.view.GestureDetector;
81 import android.view.KeyEvent;
82 import android.view.Menu;
83 import android.view.MenuItem;
84 import android.view.MotionEvent;
85 import android.view.View;
86 import android.view.ViewGroup;
87 import android.view.WindowManager;
88 import android.view.inputmethod.InputMethodManager;
89 import android.webkit.CookieManager;
90 import android.webkit.HttpAuthHandler;
91 import android.webkit.SslErrorHandler;
92 import android.webkit.ValueCallback;
93 import android.webkit.WebBackForwardList;
94 import android.webkit.WebChromeClient;
95 import android.webkit.WebResourceResponse;
96 import android.webkit.WebStorage;
97 import android.webkit.WebView;
98 import android.webkit.WebViewClient;
99 import android.webkit.WebViewDatabase;
100 import android.widget.ArrayAdapter;
101 import android.widget.CursorAdapter;
102 import android.widget.EditText;
103 import android.widget.FrameLayout;
104 import android.widget.ImageView;
105 import android.widget.LinearLayout;
106 import android.widget.ListView;
107 import android.widget.ProgressBar;
108 import android.widget.RadioButton;
109 import android.widget.RelativeLayout;
110 import android.widget.TextView;
112 import com.stoutner.privacybrowser.BuildConfig;
113 import com.stoutner.privacybrowser.R;
114 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
116 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
117 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
118 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
119 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
120 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
121 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
122 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
123 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
124 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
125 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
126 import com.stoutner.privacybrowser.helpers.AdHelper;
127 import com.stoutner.privacybrowser.helpers.BlockListHelper;
128 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
129 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
130 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
131 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
132 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
134 import java.io.ByteArrayInputStream;
135 import java.io.ByteArrayOutputStream;
137 import java.io.IOException;
138 import java.io.UnsupportedEncodingException;
139 import java.net.MalformedURLException;
141 import java.net.URLDecoder;
142 import java.net.URLEncoder;
143 import java.util.ArrayList;
144 import java.util.Date;
145 import java.util.HashMap;
146 import java.util.HashSet;
147 import java.util.List;
148 import java.util.Map;
149 import java.util.Set;
151 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
152 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
153 CreateHomeScreenShortcutDialog.CreateHomeScreenShortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
154 DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
155 HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
156 SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
158 // `darkTheme` is public static so it can be accessed from everywhere.
159 public static boolean darkTheme;
161 // `allowScreenshots` is public static so it can be accessed from everywhere. It is also used in `onCreate()`.
162 public static boolean allowScreenshots;
164 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
165 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
166 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
167 public static Bitmap favoriteIconBitmap;
169 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
170 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
171 public static String formattedUrlString;
173 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
174 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
175 public static SslCertificate sslCertificate;
177 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()` and `onResume()`.
178 public static String orbotStatus;
180 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
181 public static String webViewTitle;
183 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
184 public static String appliedUserAgentString;
186 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
187 public static boolean reloadOnRestart;
189 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`. It is also used in `onRestart()`.
190 public static boolean loadUrlOnRestart;
192 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
193 public static boolean restartFromBookmarksActivity;
195 // The block list versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
196 public static String easyListVersion;
197 public static String easyPrivacyVersion;
198 public static String fanboysAnnoyanceVersion;
199 public static String fanboysSocialVersion;
200 public static String ultraPrivacyVersion;
202 // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`. They are also used in `onCreate()` and `onPrepareOptionsMenu()`.
203 public static List<String[]> resourceRequests;
204 public static String[] whiteListResultStringArray;
206 int easyListBlockedRequests;
207 int easyPrivacyBlockedRequests;
208 int fanboysAnnoyanceListBlockedRequests;
209 int fanboysSocialBlockingListBlockedRequests;
210 int ultraPrivacyBlockedRequests;
211 int thirdPartyBlockedRequests;
213 public final static int REQUEST_DISPOSITION = 0;
214 public final static int REQUEST_URL = 1;
215 public final static int REQUEST_BLOCKLIST = 2;
216 public final static int REQUEST_SUBLIST = 3;
217 public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
218 public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
220 public final static int REQUEST_DEFAULT = 0;
221 public final static int REQUEST_ALLOWED = 1;
222 public final static int REQUEST_THIRD_PARTY = 2;
223 public final static int REQUEST_BLOCKED = 3;
225 public final static int MAIN_WHITELIST = 1;
226 public final static int FINAL_WHITELIST = 2;
227 public final static int DOMAIN_WHITELIST = 3;
228 public final static int DOMAIN_INITIAL_WHITELIST = 4;
229 public final static int DOMAIN_FINAL_WHITELIST = 5;
230 public final static int THIRD_PARTY_WHITELIST = 6;
231 public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
232 public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
234 public final static int MAIN_BLACKLIST = 9;
235 public final static int INITIAL_BLACKLIST = 10;
236 public final static int FINAL_BLACKLIST = 11;
237 public final static int DOMAIN_BLACKLIST = 12;
238 public final static int DOMAIN_INITIAL_BLACKLIST = 13;
239 public final static int DOMAIN_FINAL_BLACKLIST = 14;
240 public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
241 public final static int THIRD_PARTY_BLACKLIST = 16;
242 public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
243 public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
244 public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
245 public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
246 public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
247 public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
249 // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
250 // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
251 public static boolean blockAllThirdPartyRequests;
253 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
254 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
255 public static String currentBookmarksFolder;
257 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
258 public static int domainSettingsDatabaseId;
260 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
261 public static String pinnedDomainSslIssuedToCNameString;
262 public static String pinnedDomainSslIssuedToONameString;
263 public static String pinnedDomainSslIssuedToUNameString;
264 public static String pinnedDomainSslIssuedByCNameString;
265 public static String pinnedDomainSslIssuedByONameString;
266 public static String pinnedDomainSslIssuedByUNameString;
267 public static Date pinnedDomainSslStartDate;
268 public static Date pinnedDomainSslEndDate;
270 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
271 public final static int UNRECOGNIZED_USER_AGENT = -1;
272 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
273 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
274 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
275 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
276 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
279 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
280 private ActionBar appBar;
282 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
283 private boolean navigatingHistory;
285 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
286 private Bitmap favoriteIconDefaultBitmap;
288 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
289 private DrawerLayout drawerLayout;
291 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
292 private CoordinatorLayout rootCoordinatorLayout;
294 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
295 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
296 private WebView mainWebView;
298 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
299 private FrameLayout fullScreenVideoFrameLayout;
301 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
302 private SwipeRefreshLayout swipeRefreshLayout;
304 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
305 private RelativeLayout urlAppBarRelativeLayout;
307 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
308 private ImageView favoriteIconImageView;
310 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
311 private CookieManager cookieManager;
313 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
314 private final Map<String, String> customHeaders = new HashMap<>();
316 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
317 private boolean javaScriptEnabled;
319 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
320 private boolean firstPartyCookiesEnabled;
322 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
323 private boolean thirdPartyCookiesEnabled;
325 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
326 private boolean domStorageEnabled;
328 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`. It can be removed once the minimum API >= 26.
329 private boolean saveFormDataEnabled;
331 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
332 private boolean nightMode;
334 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
335 private boolean displayWebpageImagesBoolean;
337 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
338 private String homepage;
340 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
341 private String searchURL;
343 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
344 private Menu mainMenu;
346 // `refreshMenuItem` is used in `onCreate()` and `onCreateOptionsMenu()`.
347 private MenuItem refreshMenuItem;
349 // The blocklist menu items are used in `onCreate()`, `onCreateOptionsMenu()`, and `onPrepareOptionsMenu()`.
350 private MenuItem blocklistsMenuItem;
351 private MenuItem easyListMenuItem;
352 private MenuItem easyPrivacyMenuItem;
353 private MenuItem fanboysAnnoyanceListMenuItem;
354 private MenuItem fanboysSocialBlockingListMenuItem;
355 private MenuItem ultraPrivacyMenuItem;
356 private MenuItem blockAllThirdParyRequestsMenuItem;
358 // The blocklist variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
359 private boolean easyListEnabled;
360 private boolean easyPrivacyEnabled;
361 private boolean fanboysAnnoyanceListEnabled;
362 private boolean fanboysSocialBlockingListEnabled;
363 private boolean ultraPrivacyEnabled;
365 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
366 private Runtime privacyBrowserRuntime;
368 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
369 private boolean proxyThroughOrbot;
371 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
372 private boolean incognitoModeEnabled;
374 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
375 private boolean fullScreenBrowsingModeEnabled;
377 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
378 private boolean inFullScreenBrowsingMode;
380 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
381 private boolean hideSystemBarsOnFullscreen;
383 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
384 private boolean translucentNavigationBarOnFullscreen;
386 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
387 private boolean reapplyDomainSettingsOnRestart;
389 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
390 private boolean reapplyAppSettingsOnRestart;
392 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
393 private boolean displayingFullScreenVideo;
395 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
396 private String currentDomainName;
398 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
399 private boolean ignorePinnedSslCertificate;
401 // `orbotStatusBroadcastReciever` is used in `onCreate()` and `onDestroy()`.
402 private BroadcastReceiver orbotStatusBroadcastReceiver;
404 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyAppSettings()`.
405 private boolean waitingForOrbot;
407 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
408 private boolean domainSettingsApplied;
410 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
411 private int displayWebpageImagesInt;
413 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
414 private boolean onTheFlyDisplayImagesSet;
416 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
417 private String waitingForOrbotHTMLString;
419 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
420 private String privateDataDirectoryString;
422 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
423 private LinearLayout findOnPageLinearLayout;
425 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
426 private EditText findOnPageEditText;
428 // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
429 private boolean displayAdditionalAppBarIcons;
431 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
432 private ActionBarDrawerToggle drawerToggle;
434 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
435 private Toolbar supportAppBar;
437 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
438 private EditText urlTextBox;
440 // The color spans are used in `onCreate()` and `highlightUrlText()`.
441 private ForegroundColorSpan redColorSpan;
442 private ForegroundColorSpan initialGrayColorSpan;
443 private ForegroundColorSpan finalGrayColorSpan;
445 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
446 private SslErrorHandler sslErrorHandler;
448 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
449 private static HttpAuthHandler httpAuthHandler;
451 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
452 private InputMethodManager inputMethodManager;
454 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
455 private RelativeLayout mainWebViewRelativeLayout;
457 // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
458 private boolean urlIsLoading;
460 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
461 private boolean pinnedDomainSslCertificate;
463 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
464 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
466 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
467 private ListView bookmarksListView;
469 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
470 private TextView bookmarksTitleTextView;
472 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
473 private Cursor bookmarksCursor;
475 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
476 private CursorAdapter bookmarksCursorAdapter;
478 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
479 private String oldFolderNameString;
481 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
482 private ValueCallback<Uri[]> fileChooserCallback;
484 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
485 private String downloadUrl;
486 private String downloadContentDisposition;
487 private long downloadContentLength;
489 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
490 private String downloadImageUrl;
492 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
493 private ArrayAdapter<CharSequence> userAgentNamesArray;
494 private String[] userAgentDataArray;
496 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
497 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
498 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
501 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled. The whole premise of Privacy Browser is built around an understanding of these dangers.
502 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
503 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
504 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
505 @SuppressWarnings("deprecation")
506 protected void onCreate(Bundle savedInstanceState) {
507 // Get a handle for the shared preferences.
508 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
510 // Get the theme and screenshot preferences.
511 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
512 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
514 // Disable screenshots if not allowed.
515 if (!allowScreenshots) {
516 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
519 // Set the activity theme.
521 setTheme(R.style.PrivacyBrowserDark);
523 setTheme(R.style.PrivacyBrowserLight);
526 // Run the default commands.
527 super.onCreate(savedInstanceState);
529 // Set the content view.
530 setContentView(R.layout.main_drawerlayout);
532 // Get a handle for `inputMethodManager`.
533 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
535 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
536 supportAppBar = findViewById(R.id.app_bar);
537 setSupportActionBar(supportAppBar);
538 appBar = getSupportActionBar();
540 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
541 assert appBar != null;
543 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
544 appBar.setCustomView(R.layout.url_app_bar);
545 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
547 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
548 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
549 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
550 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
552 // Get a handle for `urlTextBox`.
553 urlTextBox = findViewById(R.id.url_edittext);
555 // Remove the formatting from `urlTextBar` when the user is editing the text.
556 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
557 if (hasFocus) { // The user is editing `urlTextBox`.
558 // Remove the highlighting.
559 urlTextBox.getText().removeSpan(redColorSpan);
560 urlTextBox.getText().removeSpan(initialGrayColorSpan);
561 urlTextBox.getText().removeSpan(finalGrayColorSpan);
562 } else { // The user has stopped editing `urlTextBox`.
563 // Reapply the highlighting.
568 // Set the go button on the keyboard to load the URL in `urlTextBox`.
569 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
570 // If the event is a key-down event on the `enter` button, load the URL.
571 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
572 // Load the URL into the mainWebView and consume the event.
574 loadUrlFromTextBox();
575 } catch (UnsupportedEncodingException e) {
578 // If the enter key was pressed, consume the event.
581 // If any other key was pressed, do not consume the event.
586 // Set `waitingForOrbotHTMLString`.
587 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
589 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
590 currentDomainName = "";
591 orbotStatus = "unknown";
592 waitingForOrbot = false;
594 // Create an Orbot status `BroadcastReceiver`.
595 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
597 public void onReceive(Context context, Intent intent) {
598 // Store the content of the status message in `orbotStatus`.
599 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
601 // If we are waiting on Orbot, load the website now that Orbot is connected.
602 if (orbotStatus.equals("ON") && waitingForOrbot) {
603 // Reset `waitingForOrbot`.
604 waitingForOrbot = false;
606 // Load `formattedUrlString
607 loadUrl(formattedUrlString);
612 // Register `orbotStatusBroadcastReceiver` on `this` context.
613 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
615 // Get handles for views that need to be accessed.
616 drawerLayout = findViewById(R.id.drawerlayout);
617 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
618 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
619 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
620 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
621 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
622 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
623 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
624 mainWebView = findViewById(R.id.main_webview);
625 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
626 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
627 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
628 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
629 favoriteIconImageView = findViewById(R.id.favorite_icon);
631 // Set the bookmarks drawer resources according to the theme. This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
633 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
634 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
635 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
636 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
638 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
639 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
640 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
641 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
644 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
645 launchBookmarksActivityFab.setOnClickListener(v -> {
646 // Create an intent to launch the bookmarks activity.
647 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
649 // Include the current folder with the `Intent`.
650 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
653 startActivity(bookmarksIntent);
656 // Set the create new bookmark folder FAB to display an alert dialog.
657 createBookmarkFolderFab.setOnClickListener(v -> {
658 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
659 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
660 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
663 // Set the create new bookmark FAB to display an alert dialog.
664 createBookmarkFab.setOnClickListener(view -> {
665 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
666 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
667 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
670 // Create a double-tap listener to toggle full-screen mode.
671 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
672 // Override `onDoubleTap()`. All other events are handled using the default settings.
674 public boolean onDoubleTap(MotionEvent event) {
675 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
676 // Toggle `inFullScreenBrowsingMode`.
677 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
679 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
680 // Hide the `appBar`.
683 // Hide the banner ad in the free flavor.
684 if (BuildConfig.FLAVOR.contentEquals("free")) {
685 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
686 AdHelper.hideAd(findViewById(R.id.adview));
689 // Modify the system bars.
690 if (hideSystemBarsOnFullscreen) { // Hide everything.
691 // Remove the translucent overlays.
692 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
694 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
695 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
697 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
698 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
699 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
701 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
703 // Set `rootCoordinatorLayout` to fill the whole screen.
704 rootCoordinatorLayout.setFitsSystemWindows(false);
705 } else { // Hide everything except the status and navigation bars.
706 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
707 rootCoordinatorLayout.setFitsSystemWindows(false);
709 // There is an Android Support Library bug that causes a scrim to print on the right side of the `Drawer Layout` when the navigation bar is displayed on the right of the screen.
710 if (translucentNavigationBarOnFullscreen) {
711 // Set the navigation bar to be translucent.
712 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
715 } else { // Switch to normal viewing mode.
716 // Show the `appBar`.
719 // Show the `BannerAd` in the free flavor.
720 if (BuildConfig.FLAVOR.contentEquals("free")) {
721 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
722 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
725 // Remove the translucent navigation bar flag if it is set.
726 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
728 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
729 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
731 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
732 rootCoordinatorLayout.setSystemUiVisibility(0);
734 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
735 rootCoordinatorLayout.setFitsSystemWindows(true);
738 // Consume the double-tap.
740 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
746 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
747 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
748 // Call `performClick()` on the view, which is required for accessibility.
751 // Send the `event` to `gestureDetector`.
752 return gestureDetector.onTouchEvent(event);
755 // Update `findOnPageCountTextView`.
756 mainWebView.setFindListener(new WebView.FindListener() {
757 // Get a handle for `findOnPageCountTextView`.
758 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
761 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
762 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
763 // Set `findOnPageCountTextView` to `0/0`.
764 findOnPageCountTextView.setText(R.string.zero_of_zero);
765 } else if (isDoneCounting) { // There are matches.
766 // `activeMatchOrdinal` is zero-based.
767 int activeMatch = activeMatchOrdinal + 1;
769 // Build the match string.
770 String matchString = activeMatch + "/" + numberOfMatches;
772 // Set `findOnPageCountTextView`.
773 findOnPageCountTextView.setText(matchString);
778 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
779 findOnPageEditText.addTextChangedListener(new TextWatcher() {
781 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
786 public void onTextChanged(CharSequence s, int start, int before, int count) {
791 public void afterTextChanged(Editable s) {
792 // Search for the text in `mainWebView`.
793 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
797 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
798 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
799 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
800 // Hide the soft keyboard. `0` indicates no additional flags.
801 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
803 // Consume the event.
805 } else { // A different key was pressed.
806 // Do not consume the event.
811 // Implement swipe to refresh
812 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
813 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
814 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
816 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
817 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
818 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
820 // Listen for touches on the navigation menu.
821 final NavigationView navigationView = findViewById(R.id.navigationview);
822 navigationView.setNavigationItemSelectedListener(this);
824 // Get handles for `navigationMenu` and the back and forward menu items. The menu is zero-based, so items 1, 2, and 3 are the second, third, and fourth entries in the menu.
825 final Menu navigationMenu = navigationView.getMenu();
826 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
827 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
828 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
829 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
831 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
832 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
833 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
835 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
836 currentBookmarksFolder = "";
838 // Load the home folder, which is `""` in the database.
839 loadBookmarksFolder();
841 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
842 // Convert the id from long to int to match the format of the bookmarks database.
843 int databaseID = (int) id;
845 // Get the bookmark cursor for this ID and move it to the first row.
846 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
847 bookmarkCursor.moveToFirst();
849 // Act upon the bookmark according to the type.
850 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
851 // Store the new folder name in `currentBookmarksFolder`.
852 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
854 // Load the new folder.
855 loadBookmarksFolder();
856 } else { // The selected bookmark is not a folder.
857 // Load the bookmark URL.
858 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
860 // Close the bookmarks drawer.
861 drawerLayout.closeDrawer(GravityCompat.END);
864 // Close the `Cursor`.
865 bookmarkCursor.close();
868 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
869 // Convert the database ID from `long` to `int`.
870 int databaseId = (int) id;
872 // Find out if the selected bookmark is a folder.
873 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
876 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
877 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
879 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
880 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
881 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
883 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
884 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
885 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
888 // Consume the event.
892 // The drawer listener is used to update the navigation menu.
893 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
895 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
899 public void onDrawerOpened(@NonNull View drawerView) {
903 public void onDrawerClosed(@NonNull View drawerView) {
907 public void onDrawerStateChanged(int newState) {
908 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
909 // Update the back, forward, history, and requests menu items.
910 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
911 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
912 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
913 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
915 // Hide the keyboard (if displayed).
916 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
918 // Clear the focus from from the URL text box.
919 urlTextBox.clearFocus();
924 // drawerToggle creates the hamburger icon at the start of the AppBar.
925 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
927 // Get a handle for the progress bar.
928 final ProgressBar progressBar = findViewById(R.id.progress_bar);
930 mainWebView.setWebChromeClient(new WebChromeClient() {
931 // Update the progress bar when a page is loading.
933 public void onProgressChanged(WebView view, int progress) {
934 // Inject the night mode CSS if night mode is enabled.
936 // `background-color: #212121` sets the background to be dark gray. `color: #BDBDBD` sets the text color to be light gray. `box-shadow: none` removes a lower underline on links
937 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
938 // `border: none` removes all borders, which can also be used to underline text.
939 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
940 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
941 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
942 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
943 // Initialize a `Handler` to display `mainWebView`.
944 Handler displayWebViewHandler = new Handler();
946 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
947 Runnable displayWebViewRunnable = () -> {
948 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
949 if (progressBar.getVisibility() == View.GONE) {
950 mainWebView.setVisibility(View.VISIBLE);
954 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
955 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
959 // Update the progress bar.
960 progressBar.setProgress(progress);
962 // Set the visibility of the progress bar.
963 if (progress < 100) {
964 // Show the progress bar.
965 progressBar.setVisibility(View.VISIBLE);
967 // Hide the progress bar.
968 progressBar.setVisibility(View.GONE);
970 // Display `mainWebView` if night mode is disabled.
971 // Because of a race condition between `applyDomainSettings` and `onPageStarted`, when night mode is set by domain settings the `WebView` may be hidden even if night mode is not
972 // currently enabled.
974 mainWebView.setVisibility(View.VISIBLE);
977 //Stop the swipe to refresh indicator if it is running
978 swipeRefreshLayout.setRefreshing(false);
982 // Set the favorite icon when it changes.
984 public void onReceivedIcon(WebView view, Bitmap icon) {
985 // Only update the favorite icon if the website has finished loading.
986 if (progressBar.getVisibility() == View.GONE) {
987 // Save a copy of the favorite icon.
988 favoriteIconBitmap = icon;
990 // Place the favorite icon in the appBar.
991 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
995 // Save a copy of the title when it changes.
997 public void onReceivedTitle(WebView view, String title) {
998 // Save a copy of the title.
999 webViewTitle = title;
1002 // Enter full screen video.
1004 public void onShowCustomView(View view, CustomViewCallback callback) {
1005 // Set the full screen video flag.
1006 displayingFullScreenVideo = true;
1008 // Pause the ad if this is the free flavor.
1009 if (BuildConfig.FLAVOR.contentEquals("free")) {
1010 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1011 AdHelper.pauseAd(findViewById(R.id.adview));
1014 // Remove the translucent overlays.
1015 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1017 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1018 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1020 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1021 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1022 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1024 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1026 // Set `rootCoordinatorLayout` to fill the entire screen.
1027 rootCoordinatorLayout.setFitsSystemWindows(false);
1029 // Disable the sliding drawers.
1030 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1032 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1033 fullScreenVideoFrameLayout.addView(view);
1034 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1037 // Exit full screen video.
1039 public void onHideCustomView() {
1040 // Unset the full screen video flag.
1041 displayingFullScreenVideo = false;
1043 // Hide `fullScreenVideoFrameLayout`.
1044 fullScreenVideoFrameLayout.removeAllViews();
1045 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1047 // Enable the sliding drawers.
1048 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1050 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1051 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1052 if (hideSystemBarsOnFullscreen) { // Hide everything.
1053 // Remove the translucent navigation setting if it is currently flagged.
1054 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1056 // Remove the translucent status bar overlay.
1057 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1059 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1060 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1062 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1063 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1064 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1066 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1067 } else { // Hide everything except the status and navigation bars.
1068 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1069 rootCoordinatorLayout.setSystemUiVisibility(0);
1071 // Add the translucent status flag if it is unset.
1072 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1074 if (translucentNavigationBarOnFullscreen) {
1075 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1076 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1078 // Set the navigation bar to be black.
1079 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1082 } else { // Switch to normal viewing mode.
1083 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1084 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1088 // Show the `BannerAd` in the free flavor.
1089 if (BuildConfig.FLAVOR.contentEquals("free")) {
1090 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1091 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1094 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1095 rootCoordinatorLayout.setSystemUiVisibility(0);
1097 // Remove the translucent navigation bar flag if it is set.
1098 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1100 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1101 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1103 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1104 rootCoordinatorLayout.setFitsSystemWindows(true);
1107 // Show the ad if this is the free flavor.
1108 if (BuildConfig.FLAVOR.contentEquals("free")) {
1109 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1110 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1116 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1117 // Show the file chooser if the device is running API >= 21.
1118 if (Build.VERSION.SDK_INT >= 21) {
1119 // Store the file path callback.
1120 fileChooserCallback = filePathCallback;
1122 // Create an intent to open a chooser based ont the file chooser parameters.
1123 Intent fileChooserIntent = fileChooserParams.createIntent();
1125 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1126 startActivityForResult(fileChooserIntent, 0);
1132 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1133 registerForContextMenu(mainWebView);
1135 // Allow the downloading of files.
1136 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1137 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1138 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1139 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1141 // Store the variables for future use by `onRequestPermissionsResult()`.
1143 downloadContentDisposition = contentDisposition;
1144 downloadContentLength = contentLength;
1146 // Show a dialog if the user has previously denied the permission.
1147 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1148 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1149 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1151 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1152 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1153 } else { // Show the permission request directly.
1154 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1155 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1157 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1158 // Get a handle for the download file alert dialog.
1159 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1161 // Show the download file alert dialog.
1162 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1166 // Allow pinch to zoom.
1167 mainWebView.getSettings().setBuiltInZoomControls(true);
1169 // Hide zoom controls.
1170 mainWebView.getSettings().setDisplayZoomControls(false);
1172 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1173 mainWebView.getSettings().setUseWideViewPort(true);
1175 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1176 mainWebView.getSettings().setLoadWithOverviewMode(true);
1178 // Explicitly disable geolocation.
1179 mainWebView.getSettings().setGeolocationEnabled(false);
1181 // Initialize cookieManager.
1182 cookieManager = CookieManager.getInstance();
1184 // Replace the header that `WebView` creates for `X-Requested-With` with a null value. The default value is the application ID (com.stoutner.privacybrowser.standard).
1185 customHeaders.put("X-Requested-With", "");
1187 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1188 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1190 // Get the intent that started the app.
1191 final Intent launchingIntent = getIntent();
1193 // Extract the launching intent data as `launchingIntentUriData`.
1194 final Uri launchingIntentUriData = launchingIntent.getData();
1196 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1197 if (launchingIntentUriData != null) {
1198 formattedUrlString = launchingIntentUriData.toString();
1201 // Get a handle for the `Runtime`.
1202 privacyBrowserRuntime = Runtime.getRuntime();
1204 // Store the application's private data directory.
1205 privateDataDirectoryString = getApplicationInfo().dataDir;
1206 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1208 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1209 inFullScreenBrowsingMode = false;
1211 // Initialize the privacy settings variables.
1212 javaScriptEnabled = false;
1213 firstPartyCookiesEnabled = false;
1214 thirdPartyCookiesEnabled = false;
1215 domStorageEnabled = false;
1216 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1219 // Initialize the WebView title.
1220 webViewTitle = getString(R.string.no_title);
1222 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1223 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1224 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1225 assert favoriteIconBitmapDrawable != null;
1226 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1228 // If the favorite icon is null, load the default.
1229 if (favoriteIconBitmap == null) {
1230 favoriteIconBitmap = favoriteIconDefaultBitmap;
1233 // Initialize the user agent array adapter and string array.
1234 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1235 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1237 // Apply the app settings from the shared preferences.
1240 // Instantiate the block list helper.
1241 BlockListHelper blockListHelper = new BlockListHelper();
1243 // Initialize the list of resource requests.
1244 resourceRequests = new ArrayList<>();
1246 // Parse the block lists.
1247 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1248 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1249 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1250 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1251 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1253 // Store the list versions.
1254 easyListVersion = easyList.get(0).get(0)[0];
1255 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1256 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1257 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1258 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1260 // Get a handle for the activity. This is used to update the requests counter while the navigation menu is open.
1261 Activity activity = this;
1263 mainWebView.setWebViewClient(new WebViewClient() {
1264 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1265 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1266 @SuppressWarnings("deprecation")
1268 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1269 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1270 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1271 formattedUrlString = "";
1273 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1274 applyDomainSettings(url, true, false);
1276 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1278 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1279 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1280 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1282 // Parse the url and set it as the data for the intent.
1283 emailIntent.setData(Uri.parse(url));
1285 // Open the email program in a new task instead of as part of Privacy Browser.
1286 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1289 startActivity(emailIntent);
1291 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1293 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1294 // Open the dialer and load the phone number, but wait for the user to place the call.
1295 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1297 // Add the phone number to the intent.
1298 dialIntent.setData(Uri.parse(url));
1300 // Open the dialer in a new task instead of as part of Privacy Browser.
1301 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1304 startActivity(dialIntent);
1306 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1308 } else { // Load a system chooser to select an app that can handle the URL.
1309 // Open an app that can handle the URL.
1310 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1312 // Add the URL to the intent.
1313 genericIntent.setData(Uri.parse(url));
1315 // List all apps that can handle the URL instead of just opening the first one.
1316 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1318 // Open the app in a new task instead of as part of Privacy Browser.
1319 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1321 // Start the app or display a snackbar if no app is available to handle the URL.
1323 startActivity(genericIntent);
1324 } catch (ActivityNotFoundException exception) {
1325 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1328 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1333 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1334 @SuppressWarnings("deprecation")
1336 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1337 // Create an empty web resource response to be used if the resource request is blocked.
1338 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1340 // Reset the whitelist results tracker.
1341 whiteListResultStringArray = null;
1343 // Initialize the third party request tracker.
1344 boolean isThirdPartyRequest = false;
1346 // Initialize the current domain string.
1347 String currentDomain = "";
1349 // Nobody is happy when comparing null strings.
1350 if (!(formattedUrlString == null) && !(url == null)) {
1351 // Get the domain strings to URIs.
1352 Uri currentDomainUri = Uri.parse(formattedUrlString);
1353 Uri requestDomainUri = Uri.parse(url);
1355 // Get the domain host names.
1356 String currentBaseDomain = currentDomainUri.getHost();
1357 String requestBaseDomain = requestDomainUri.getHost();
1359 // Update the current domain variable.
1360 currentDomain = currentBaseDomain;
1362 // Only compare the current base domain and the request base domain if neither is null.
1363 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1364 // Determine the current base domain.
1365 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1366 // Remove the first subdomain.
1367 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1370 // Determine the request base domain.
1371 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1372 // Remove the first subdomain.
1373 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1376 // Update the third party request tracker.
1377 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1381 // Block third-party requests if enabled.
1382 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1383 // Increment the blocked requests counters.
1385 thirdPartyBlockedRequests++;
1387 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1388 activity.runOnUiThread(() -> {
1389 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1390 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1391 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1394 // Add the request to the log.
1395 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1397 // Return an empty web resource response.
1398 return emptyWebResourceResponse;
1401 // Check UltraPrivacy if it is enabled.
1402 if (ultraPrivacyEnabled) {
1403 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1404 // Increment the blocked requests counters.
1406 ultraPrivacyBlockedRequests++;
1408 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1409 activity.runOnUiThread(() -> {
1410 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1411 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1412 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1415 // The resource request was blocked. Return an empty web resource response.
1416 return emptyWebResourceResponse;
1419 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1420 if (whiteListResultStringArray != null) {
1421 // Add a whitelist entry to the resource requests array.
1422 resourceRequests.add(whiteListResultStringArray);
1424 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1429 // Check EasyList if it is enabled.
1430 if (easyListEnabled) {
1431 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1432 // Increment the blocked requests counters.
1434 easyListBlockedRequests++;
1436 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1437 activity.runOnUiThread(() -> {
1438 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1439 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1440 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1443 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1444 whiteListResultStringArray = null;
1446 // The resource request was blocked. Return an empty web resource response.
1447 return emptyWebResourceResponse;
1451 // Check EasyPrivacy if it is enabled.
1452 if (easyPrivacyEnabled) {
1453 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1454 // Increment the blocked requests counters.
1456 easyPrivacyBlockedRequests++;
1458 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1459 activity.runOnUiThread(() -> {
1460 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1461 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1462 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1465 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1466 whiteListResultStringArray = null;
1468 // The resource request was blocked. Return an empty web resource response.
1469 return emptyWebResourceResponse;
1473 // Check Fanboy’s Annoyance List if it is enabled.
1474 if (fanboysAnnoyanceListEnabled) {
1475 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1476 // Increment the blocked requests counters.
1478 fanboysAnnoyanceListBlockedRequests++;
1480 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1481 activity.runOnUiThread(() -> {
1482 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1483 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1484 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1487 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1488 whiteListResultStringArray = null;
1490 // The resource request was blocked. Return an empty web resource response.
1491 return emptyWebResourceResponse;
1493 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1494 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1495 // Increment the blocked requests counters.
1497 fanboysSocialBlockingListBlockedRequests++;
1499 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1500 activity.runOnUiThread(() -> {
1501 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1502 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1503 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1506 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1507 whiteListResultStringArray = null;
1509 // The resource request was blocked. Return an empty web resource response.
1510 return emptyWebResourceResponse;
1514 // Add the request to the log because it hasn't been processed by any of the previous checks.
1515 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1516 resourceRequests.add(whiteListResultStringArray);
1517 } else { // The request didn't match any blocklist entry. Log it as a defult request.
1518 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1521 // The resource request has not been blocked. `return null` loads the requested resource.
1525 // Handle HTTP authentication requests.
1527 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1528 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1529 httpAuthHandler = handler;
1531 // Display the HTTP authentication dialog.
1532 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1533 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1536 // Update the URL in urlTextBox when the page starts to load.
1538 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1539 // Reset the list of resource requests.
1540 resourceRequests.clear();
1542 // Initialize the counters for requests blocked by each blocklist.
1543 blockedRequests = 0;
1544 easyListBlockedRequests = 0;
1545 easyPrivacyBlockedRequests = 0;
1546 fanboysAnnoyanceListBlockedRequests = 0;
1547 fanboysSocialBlockingListBlockedRequests = 0;
1548 ultraPrivacyBlockedRequests = 0;
1549 thirdPartyBlockedRequests = 0;
1551 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1553 mainWebView.setVisibility(View.INVISIBLE);
1556 // Hide the keyboard. `0` indicates no additional flags.
1557 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1559 // Check to see if Privacy Browser is waiting on Orbot.
1560 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1561 // We need to update `formattedUrlString` at the beginning of the load, so that if the user toggles JavaScript during the load the new website is reloaded.
1562 formattedUrlString = url;
1564 // Display the formatted URL text.
1565 urlTextBox.setText(formattedUrlString);
1567 // Apply text highlighting to `urlTextBox`.
1570 // Apply any custom domain settings if the URL was loaded by navigating history.
1571 if (navigatingHistory) {
1572 // Reset `navigatingHistory`.
1573 navigatingHistory = false;
1575 // Apply the domain settings.
1576 applyDomainSettings(url, true, false);
1579 // Set `urlIsLoading` to `true`, so that redirects while loading do not trigger changes in the user agent, which forces another reload of the existing page.
1580 urlIsLoading = true;
1582 // Replace Refresh with Stop if the menu item has been created. (The WebView typically begins loading before the menu items are instantiated.)
1583 if (refreshMenuItem != null) {
1585 refreshMenuItem.setTitle(R.string.stop);
1587 // If the icon is displayed in the AppBar, set it according to the theme.
1588 if (displayAdditionalAppBarIcons) {
1590 refreshMenuItem.setIcon(R.drawable.close_dark);
1592 refreshMenuItem.setIcon(R.drawable.close_light);
1599 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1601 public void onPageFinished(WebView view, String url) {
1602 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1603 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1604 cookieManager.flush();
1607 // Update the Refresh menu item if it has been created.
1608 if (refreshMenuItem != null) {
1609 // Reset the Refresh title.
1610 refreshMenuItem.setTitle(R.string.refresh);
1612 // If the icon is displayed in the AppBar, reset it according to the theme.
1613 if (displayAdditionalAppBarIcons) {
1615 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1617 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1622 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1623 urlIsLoading = false;
1625 // Clear the cache and history if Incognito Mode is enabled.
1626 if (incognitoModeEnabled) {
1627 // Clear the cache. `true` includes disk files.
1628 mainWebView.clearCache(true);
1630 // Clear the back/forward history.
1631 mainWebView.clearHistory();
1633 // Manually delete cache folders.
1635 // Delete the main cache directory.
1636 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1638 // Delete the secondary `Service Worker` cache directory.
1639 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1640 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1641 } catch (IOException e) {
1642 // Do nothing if an error is thrown.
1646 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1647 if (!waitingForOrbot) {
1648 // Check to see if `WebView` has set `url` to be `about:blank`.
1649 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1650 // Set `formattedUrlString` to `""`.
1651 formattedUrlString = "";
1653 urlTextBox.setText(formattedUrlString);
1655 // Request focus for `urlTextBox`.
1656 urlTextBox.requestFocus();
1658 // Display the keyboard.
1659 inputMethodManager.showSoftInput(urlTextBox, 0);
1661 // Apply the domain settings. This clears any settings from the previous domain.
1662 applyDomainSettings(formattedUrlString, true, false);
1663 } else { // `WebView` has loaded a webpage.
1664 // Set `formattedUrlString`.
1665 formattedUrlString = url;
1667 // Only update `urlTextBox` if the user is not typing in it.
1668 if (!urlTextBox.hasFocus()) {
1669 // Display the formatted URL text.
1670 urlTextBox.setText(formattedUrlString);
1672 // Apply text highlighting to `urlTextBox`.
1677 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1678 sslCertificate = mainWebView.getCertificate();
1680 // Check the current website SSL certificate against the pinned SSL certificate if there is a pinned SSL certificate the user has not chosen to ignore it for this session.
1681 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1682 // Initialize the current SSL certificate variables.
1683 String currentWebsiteIssuedToCName = "";
1684 String currentWebsiteIssuedToOName = "";
1685 String currentWebsiteIssuedToUName = "";
1686 String currentWebsiteIssuedByCName = "";
1687 String currentWebsiteIssuedByOName = "";
1688 String currentWebsiteIssuedByUName = "";
1689 Date currentWebsiteSslStartDate = null;
1690 Date currentWebsiteSslEndDate = null;
1693 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1694 if (sslCertificate != null) {
1695 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1696 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1697 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1698 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1699 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1700 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1701 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1702 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1705 // Initialize `String` variables to store the SSL certificate dates. `Strings` are needed to compare the values below, which doesn't work with `Dates` if they are `null`.
1706 String currentWebsiteSslStartDateString = "";
1707 String currentWebsiteSslEndDateString = "";
1708 String pinnedDomainSslStartDateString = "";
1709 String pinnedDomainSslEndDateString = "";
1711 // Convert the `Dates` to `Strings` if they are not `null`.
1712 if (currentWebsiteSslStartDate != null) {
1713 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1716 if (currentWebsiteSslEndDate != null) {
1717 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1720 if (pinnedDomainSslStartDate != null) {
1721 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1724 if (pinnedDomainSslEndDate != null) {
1725 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1728 // Check to see if the pinned SSL certificate matches the current website certificate.
1729 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1730 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1731 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1732 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1733 // The pinned SSL certificate doesn't match the current domain certificate.
1734 //Display the pinned SSL certificate mismatch `AlertDialog`.
1735 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1736 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1742 // Handle SSL Certificate errors.
1744 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1745 // Get the current website SSL certificate.
1746 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1748 // Extract the individual pieces of information from the current website SSL certificate.
1749 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1750 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1751 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1752 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1753 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1754 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1755 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1756 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1758 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1759 if (pinnedDomainSslCertificate &&
1760 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1761 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1762 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1763 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1764 // An SSL certificate is pinned and matches the current domain certificate.
1765 // Proceed to the website without displaying an error.
1767 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1768 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1769 sslErrorHandler = handler;
1771 // Display the SSL error `AlertDialog`.
1772 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1773 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1778 // Load the website if not waiting for Orbot to connect.
1779 if (!waitingForOrbot) {
1780 loadUrl(formattedUrlString);
1785 protected void onNewIntent(Intent intent) {
1786 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1789 // Check to see if the intent contains a new URL.
1790 if (intent.getData() != null) {
1791 // Get the intent data.
1792 final Uri intentUriData = intent.getData();
1794 // Load the website.
1795 loadUrl(intentUriData.toString());
1797 // Close the navigation drawer if it is open.
1798 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1799 drawerLayout.closeDrawer(GravityCompat.START);
1802 // Close the bookmarks drawer if it is open.
1803 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1804 drawerLayout.closeDrawer(GravityCompat.END);
1807 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1808 mainWebView.requestFocus();
1813 public void onRestart() {
1814 // Run the default commands.
1817 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1818 if (proxyThroughOrbot) {
1819 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1820 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1822 // Send the intent to the Orbot package.
1823 orbotIntent.setPackage("org.torproject.android");
1826 sendBroadcast(orbotIntent);
1829 // Apply the app settings if returning from the Settings activity..
1830 if (reapplyAppSettingsOnRestart) {
1831 // Apply the app settings.
1834 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1835 if (reloadOnRestart) {
1836 // Reload `mainWebView`.
1837 mainWebView.reload();
1839 // Reset `reloadOnRestartBoolean`.
1840 reloadOnRestart = false;
1843 // Reset the return from settings flag.
1844 reapplyAppSettingsOnRestart = false;
1847 // Apply the domain settings if returning from the Domains activity.
1848 if (reapplyDomainSettingsOnRestart) {
1849 // Reapply the domain settings.
1850 applyDomainSettings(formattedUrlString, false, true);
1852 // Reset `reapplyDomainSettingsOnRestart`.
1853 reapplyDomainSettingsOnRestart = false;
1856 // Load the URL on restart to apply changes to night mode.
1857 if (loadUrlOnRestart) {
1858 // Load the current `formattedUrlString`.
1859 loadUrl(formattedUrlString);
1861 // Reset `loadUrlOnRestart.
1862 loadUrlOnRestart = false;
1865 // Update the bookmarks drawer if returning from the Bookmarks activity.
1866 if (restartFromBookmarksActivity) {
1867 // Close the bookmarks drawer.
1868 drawerLayout.closeDrawer(GravityCompat.END);
1870 // Reload the bookmarks drawer.
1871 loadBookmarksFolder();
1873 // Reset `restartFromBookmarksActivity`.
1874 restartFromBookmarksActivity = false;
1877 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1878 updatePrivacyIcons(true);
1881 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1883 public void onResume() {
1884 // Run the default commands.
1887 // Resume JavaScript (if enabled).
1888 mainWebView.resumeTimers();
1890 // Resume `mainWebView`.
1891 mainWebView.onResume();
1893 // Resume the adView for the free flavor.
1894 if (BuildConfig.FLAVOR.contentEquals("free")) {
1896 AdHelper.resumeAd(findViewById(R.id.adview));
1899 // Display a message to the user if waiting for Orbot.
1900 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1901 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1902 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1905 if (displayingFullScreenVideo) {
1906 // Remove the translucent overlays.
1907 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1909 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1910 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1912 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1913 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1914 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1916 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1921 public void onPause() {
1922 // Run the default commands.
1925 // Pause `mainWebView`.
1926 mainWebView.onPause();
1928 // Stop all JavaScript.
1929 mainWebView.pauseTimers();
1931 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1932 if (BuildConfig.FLAVOR.contentEquals("free")) {
1934 AdHelper.pauseAd(findViewById(R.id.adview));
1939 public void onDestroy() {
1940 // Unregister the Orbot status broadcast receiver.
1941 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1943 // Run the default commands.
1948 public boolean onCreateOptionsMenu(Menu menu) {
1949 // Inflate the menu; this adds items to the action bar if it is present.
1950 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1952 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1955 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1956 updatePrivacyIcons(false);
1958 // Get handles for the menu items.
1959 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1960 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1961 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1962 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1963 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1964 refreshMenuItem = menu.findItem(R.id.refresh);
1965 blocklistsMenuItem = menu.findItem(R.id.blocklists);
1966 easyListMenuItem = menu.findItem(R.id.easylist);
1967 easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1968 fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1969 fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1970 ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1971 blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1972 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1974 // Only display third-party cookies if API >= 21
1975 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1977 // Only display the form data menu items if the API < 26.
1978 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1979 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1981 // Only show Ad Consent if this is the free flavor.
1982 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1984 // Get the shared preference values.
1985 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1987 // Get the status of the additional AppBar icons.
1988 displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1990 // Set the status of the additional app bar icons. Setting the refresh menu item to `SHOW_AS_ACTION_ALWAYS` makes it appear even on small devices like phones.
1991 if (displayAdditionalAppBarIcons) {
1992 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1993 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1994 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1995 } else { //Do not display the additional icons.
1996 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1997 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1998 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2001 // Replace Refresh with Stop if a URL is already loading.
2004 refreshMenuItem.setTitle(R.string.stop);
2006 // If the icon is displayed in the AppBar, set it according to the theme.
2007 if (displayAdditionalAppBarIcons) {
2009 refreshMenuItem.setIcon(R.drawable.close_dark);
2011 refreshMenuItem.setIcon(R.drawable.close_light);
2020 public boolean onPrepareOptionsMenu(Menu menu) {
2021 // Get handles for the menu items.
2022 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2023 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2024 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2025 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2026 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
2027 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2028 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2029 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2030 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
2031 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2032 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
2033 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2035 // Set the text for the domain menu item.
2036 if (domainSettingsApplied) {
2037 addOrEditDomain.setTitle(R.string.edit_domain_settings);
2039 addOrEditDomain.setTitle(R.string.add_domain_settings);
2042 // Set the status of the menu item checkboxes.
2043 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2044 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2045 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2046 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
2047 easyListMenuItem.setChecked(easyListEnabled);
2048 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
2049 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
2050 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
2051 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
2052 blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
2053 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
2054 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2056 // Enable third-party cookies if first-party cookies are enabled.
2057 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2059 // Enable DOM Storage if JavaScript is enabled.
2060 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2062 // Enable Clear Cookies if there are any.
2063 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2065 // Get a count of the number of files in the Local Storage directory.
2066 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2067 int localStorageDirectoryNumberOfFiles = 0;
2068 if (localStorageDirectory.exists()) {
2069 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2072 // Get a count of the number of files in the IndexedDB directory.
2073 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2074 int indexedDBDirectoryNumberOfFiles = 0;
2075 if (indexedDBDirectory.exists()) {
2076 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2079 // Enable Clear DOM Storage if there is any.
2080 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2082 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
2083 if (Build.VERSION.SDK_INT < 26) {
2084 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2085 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2087 // Disable clear form data because it is not supported on current version of Android.
2088 clearFormDataMenuItem.setEnabled(false);
2091 // Enable Clear Data if any of the submenu items are enabled.
2092 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2094 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2095 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2097 // Initialize the display names for the blocklists with the number of blocked requests.
2098 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
2099 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2100 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2101 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2102 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2103 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2104 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2106 // Initialize font size variables.
2107 int fontSize = mainWebView.getSettings().getTextZoom();
2108 String fontSizeTitle;
2109 MenuItem selectedFontSizeMenuItem;
2111 // Prepare the font size title and current size menu item.
2114 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2115 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2119 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2120 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2124 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2125 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2129 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2130 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2134 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2135 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2139 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2140 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2144 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2145 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2149 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2150 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2154 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2155 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2159 // Set the font size title and select the current size menu item.
2160 fontSizeMenuItem.setTitle(fontSizeTitle);
2161 selectedFontSizeMenuItem.setChecked(true);
2163 // Run all the other default commands.
2164 super.onPrepareOptionsMenu(menu);
2166 // Display the menu.
2171 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2172 @SuppressLint("SetJavaScriptEnabled")
2173 // removeAllCookies is deprecated, but it is required for API < 21.
2174 @SuppressWarnings("deprecation")
2175 public boolean onOptionsItemSelected(MenuItem menuItem) {
2176 // Get the selected menu item ID.
2177 int menuItemId = menuItem.getItemId();
2179 // Set the commands that relate to the menu entries.
2180 switch (menuItemId) {
2181 case R.id.toggle_javascript:
2182 // Switch the status of javaScriptEnabled.
2183 javaScriptEnabled = !javaScriptEnabled;
2185 // Apply the new JavaScript status.
2186 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2188 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2189 updatePrivacyIcons(true);
2191 // Display a `Snackbar`.
2192 if (javaScriptEnabled) { // JavaScrip is enabled.
2193 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2194 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2195 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2196 } else { // Privacy mode.
2197 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2200 // Reload the WebView.
2201 mainWebView.reload();
2204 case R.id.add_or_edit_domain:
2205 if (domainSettingsApplied) { // Edit the current domain settings.
2206 // Reapply the domain settings on returning to `MainWebViewActivity`.
2207 reapplyDomainSettingsOnRestart = true;
2208 currentDomainName = "";
2210 // Create an intent to launch the domains activity.
2211 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2213 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2214 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2215 domainsIntent.putExtra("closeOnBack", true);
2218 startActivity(domainsIntent);
2219 } else { // Add a new domain.
2220 // Apply the new domain settings on returning to `MainWebViewActivity`.
2221 reapplyDomainSettingsOnRestart = true;
2222 currentDomainName = "";
2224 // Get the current domain
2225 Uri currentUri = Uri.parse(formattedUrlString);
2226 String currentDomain = currentUri.getHost();
2228 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2229 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2231 // Create the domain and store the database ID.
2232 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2234 // Create an intent to launch the domains activity.
2235 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2237 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2238 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2239 domainsIntent.putExtra("closeOnBack", true);
2242 startActivity(domainsIntent);
2246 case R.id.toggle_first_party_cookies:
2247 // Switch the status of firstPartyCookiesEnabled.
2248 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2250 // Update the menu checkbox.
2251 menuItem.setChecked(firstPartyCookiesEnabled);
2253 // Apply the new cookie status.
2254 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2256 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2257 updatePrivacyIcons(true);
2259 // Display a `Snackbar`.
2260 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2261 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2262 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2263 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2264 } else { // Privacy mode.
2265 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2268 // Reload the WebView.
2269 mainWebView.reload();
2272 case R.id.toggle_third_party_cookies:
2273 if (Build.VERSION.SDK_INT >= 21) {
2274 // Switch the status of thirdPartyCookiesEnabled.
2275 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2277 // Update the menu checkbox.
2278 menuItem.setChecked(thirdPartyCookiesEnabled);
2280 // Apply the new cookie status.
2281 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2283 // Display a `Snackbar`.
2284 if (thirdPartyCookiesEnabled) {
2285 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2287 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2290 // Reload the WebView.
2291 mainWebView.reload();
2292 } // Else do nothing because SDK < 21.
2295 case R.id.toggle_dom_storage:
2296 // Switch the status of domStorageEnabled.
2297 domStorageEnabled = !domStorageEnabled;
2299 // Update the menu checkbox.
2300 menuItem.setChecked(domStorageEnabled);
2302 // Apply the new DOM Storage status.
2303 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2305 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2306 updatePrivacyIcons(true);
2308 // Display a `Snackbar`.
2309 if (domStorageEnabled) {
2310 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2312 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2315 // Reload the WebView.
2316 mainWebView.reload();
2319 // Form data can be removed once the minimum API >= 26.
2320 case R.id.toggle_save_form_data:
2321 // Switch the status of saveFormDataEnabled.
2322 saveFormDataEnabled = !saveFormDataEnabled;
2324 // Update the menu checkbox.
2325 menuItem.setChecked(saveFormDataEnabled);
2327 // Apply the new form data status.
2328 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2330 // Display a `Snackbar`.
2331 if (saveFormDataEnabled) {
2332 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2334 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2337 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2338 updatePrivacyIcons(true);
2340 // Reload the WebView.
2341 mainWebView.reload();
2344 case R.id.clear_cookies:
2345 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2346 .setAction(R.string.undo, v -> {
2347 // Do nothing because everything will be handled by `onDismissed()` below.
2349 .addCallback(new Snackbar.Callback() {
2351 public void onDismissed(Snackbar snackbar, int event) {
2353 // The user pushed the `Undo` button.
2354 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2358 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2360 // `cookieManager.removeAllCookie()` varies by SDK.
2361 if (Build.VERSION.SDK_INT < 21) {
2362 cookieManager.removeAllCookie();
2364 // `null` indicates no callback.
2365 cookieManager.removeAllCookies(null);
2373 case R.id.clear_dom_storage:
2374 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2375 .setAction(R.string.undo, v -> {
2376 // Do nothing because everything will be handled by `onDismissed()` below.
2378 .addCallback(new Snackbar.Callback() {
2380 public void onDismissed(Snackbar snackbar, int event) {
2382 // The user pushed the `Undo` button.
2383 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2387 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2389 // Delete the DOM Storage.
2390 WebStorage webStorage = WebStorage.getInstance();
2391 webStorage.deleteAllData();
2393 // Manually delete the DOM storage files and directories.
2395 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2396 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2398 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2399 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2400 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2401 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2402 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2403 } catch (IOException e) {
2404 // Do nothing if an error is thrown.
2412 // Form data can be remove once the minimum API >= 26.
2413 case R.id.clear_form_data:
2414 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2415 .setAction(R.string.undo, v -> {
2416 // Do nothing because everything will be handled by `onDismissed()` below.
2418 .addCallback(new Snackbar.Callback() {
2420 public void onDismissed(Snackbar snackbar, int event) {
2422 // The user pushed the `Undo` button.
2423 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2427 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2429 // Delete the form data.
2430 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2431 mainWebViewDatabase.clearFormData();
2438 case R.id.font_size_twenty_five_percent:
2439 mainWebView.getSettings().setTextZoom(25);
2442 case R.id.font_size_fifty_percent:
2443 mainWebView.getSettings().setTextZoom(50);
2446 case R.id.font_size_seventy_five_percent:
2447 mainWebView.getSettings().setTextZoom(75);
2450 case R.id.font_size_one_hundred_percent:
2451 mainWebView.getSettings().setTextZoom(100);
2454 case R.id.font_size_one_hundred_twenty_five_percent:
2455 mainWebView.getSettings().setTextZoom(125);
2458 case R.id.font_size_one_hundred_fifty_percent:
2459 mainWebView.getSettings().setTextZoom(150);
2462 case R.id.font_size_one_hundred_seventy_five_percent:
2463 mainWebView.getSettings().setTextZoom(175);
2466 case R.id.font_size_two_hundred_percent:
2467 mainWebView.getSettings().setTextZoom(200);
2470 case R.id.swipe_to_refresh:
2471 // Toggle swipe to refresh.
2472 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2475 case R.id.display_images:
2476 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2477 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2478 mainWebView.reload();
2479 } else { // Images are not currently loaded automatically.
2480 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2483 // Set `onTheFlyDisplayImagesSet`.
2484 onTheFlyDisplayImagesSet = true;
2487 case R.id.view_source:
2488 // Launch the View Source activity.
2489 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2490 startActivity(viewSourceIntent);
2494 // Toggle the EasyList status.
2495 easyListEnabled = !easyListEnabled;
2497 // Update the menu checkbox.
2498 menuItem.setChecked(easyListEnabled);
2500 // Reload the main WebView.
2501 mainWebView.reload();
2504 case R.id.easyprivacy:
2505 // Toggle the EasyPrivacy status.
2506 easyPrivacyEnabled = !easyPrivacyEnabled;
2508 // Update the menu checkbox.
2509 menuItem.setChecked(easyPrivacyEnabled);
2511 // Reload the main WebView.
2512 mainWebView.reload();
2515 case R.id.fanboys_annoyance_list:
2516 // Toggle Fanboy's Annoyance List status.
2517 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2519 // Update the menu checkbox.
2520 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2522 // Update the staus of Fanboy's Social Blocking List.
2523 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2524 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2526 // Reload the main WebView.
2527 mainWebView.reload();
2530 case R.id.fanboys_social_blocking_list:
2531 // Toggle Fanboy's Social Blocking List status.
2532 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2534 // Update the menu checkbox.
2535 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2537 // Reload the main WebView.
2538 mainWebView.reload();
2541 case R.id.ultraprivacy:
2542 // Toggle the UltraPrivacy status.
2543 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2545 // Update the menu checkbox.
2546 menuItem.setChecked(ultraPrivacyEnabled);
2548 // Reload the main WebView.
2549 mainWebView.reload();
2552 case R.id.block_all_third_party_requests:
2553 //Toggle the third-party requests blocker status.
2554 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2556 // Update the menu checkbox.
2557 menuItem.setChecked(blockAllThirdPartyRequests);
2559 // Reload the main WebView.
2560 mainWebView.reload();
2564 // Setup the share string.
2565 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2567 // Create the share intent.
2568 Intent shareIntent = new Intent();
2569 shareIntent.setAction(Intent.ACTION_SEND);
2570 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2571 shareIntent.setType("text/plain");
2574 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2577 case R.id.find_on_page:
2578 // Hide the URL app bar.
2579 supportAppBar.setVisibility(View.GONE);
2581 // Show the Find on Page `RelativeLayout`.
2582 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2584 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2585 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2586 findOnPageEditText.postDelayed(() -> {
2587 // Set the focus on `findOnPageEditText`.
2588 findOnPageEditText.requestFocus();
2590 // Display the keyboard. `0` sets no input flags.
2591 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2596 // Get a `PrintManager` instance.
2597 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2599 // Convert `mainWebView` to `printDocumentAdapter`.
2600 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2602 // Remove the lint error below that `printManager` might be `null`.
2603 assert printManager != null;
2605 // Print the document. The print attributes are `null`.
2606 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2609 case R.id.add_to_homescreen:
2610 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2611 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2612 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2614 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2618 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2619 // Reload the WebView.
2620 mainWebView.reload();
2621 } else { // The stop button was pushed.
2622 // Stop the loading of the WebView.
2623 mainWebView.stopLoading();
2627 case R.id.ad_consent:
2628 // Display the ad consent dialog.
2629 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2630 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2634 // Don't consume the event.
2635 return super.onOptionsItemSelected(menuItem);
2639 // removeAllCookies is deprecated, but it is required for API < 21.
2640 @SuppressWarnings("deprecation")
2642 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2643 int menuItemId = menuItem.getItemId();
2645 switch (menuItemId) {
2651 if (mainWebView.canGoBack()) {
2652 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2653 formattedUrlString = "";
2655 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2656 navigatingHistory = true;
2658 // Load the previous website in the history.
2659 mainWebView.goBack();
2664 if (mainWebView.canGoForward()) {
2665 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2666 formattedUrlString = "";
2668 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2669 navigatingHistory = true;
2671 // Load the next website in the history.
2672 mainWebView.goForward();
2677 // Get the `WebBackForwardList`.
2678 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2680 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2681 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2682 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2686 // Launch the requests activity.
2687 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2688 startActivity(requestsIntent);
2691 case R.id.downloads:
2692 // Launch the system Download Manager.
2693 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2695 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2696 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2698 startActivity(downloadManagerIntent);
2702 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2703 reapplyDomainSettingsOnRestart = true;
2704 currentDomainName = "";
2706 // Launch the domains activity.
2707 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2708 startActivity(domainsIntent);
2712 // Set the flag to reapply app settings on restart when returning from Settings.
2713 reapplyAppSettingsOnRestart = true;
2715 // Set the flag to reapply the domain settings on restart when returning from Settings.
2716 reapplyDomainSettingsOnRestart = true;
2717 currentDomainName = "";
2719 // Launch the settings activity.
2720 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2721 startActivity(settingsIntent);
2725 // Launch `GuideActivity`.
2726 Intent guideIntent = new Intent(this, GuideActivity.class);
2727 startActivity(guideIntent);
2731 // Launch `AboutActivity`.
2732 Intent aboutIntent = new Intent(this, AboutActivity.class);
2733 startActivity(aboutIntent);
2736 case R.id.clearAndExit:
2737 // Get a handle for `sharedPreferences`. `this` references the current context.
2738 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2740 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2743 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2744 // The command to remove cookies changed slightly in API 21.
2745 if (Build.VERSION.SDK_INT >= 21) {
2746 cookieManager.removeAllCookies(null);
2748 cookieManager.removeAllCookie();
2751 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2753 // We have to use two commands because `Runtime.exec()` does not like `*`.
2754 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2755 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2756 } catch (IOException e) {
2757 // Do nothing if an error is thrown.
2761 // Clear DOM storage.
2762 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2763 // Ask `WebStorage` to clear the DOM storage.
2764 WebStorage webStorage = WebStorage.getInstance();
2765 webStorage.deleteAllData();
2767 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2769 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2770 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2772 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2773 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2774 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2775 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2776 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2777 } catch (IOException e) {
2778 // Do nothing if an error is thrown.
2782 // Clear form data if the API < 26.
2783 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2784 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2785 webViewDatabase.clearFormData();
2787 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2789 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2790 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2791 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2792 } catch (IOException e) {
2793 // Do nothing if an error is thrown.
2798 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2799 // `true` includes disk files.
2800 mainWebView.clearCache(true);
2802 // Manually delete the cache directories.
2804 // Delete the main cache directory.
2805 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2807 // Delete the secondary `Service Worker` cache directory.
2808 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2809 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2810 } catch (IOException e) {
2811 // Do nothing if an error is thrown.
2815 // Clear SSL certificate preferences.
2816 mainWebView.clearSslPreferences();
2818 // Clear the back/forward history.
2819 mainWebView.clearHistory();
2821 // Clear `formattedUrlString`.
2822 formattedUrlString = null;
2824 // Clear `customHeaders`.
2825 customHeaders.clear();
2827 // Detach all views from `mainWebViewRelativeLayout`.
2828 mainWebViewRelativeLayout.removeAllViews();
2830 // Destroy the internal state of `mainWebView`.
2831 mainWebView.destroy();
2833 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2834 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2835 if (clearEverything) {
2837 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2838 } catch (IOException e) {
2839 // Do nothing if an error is thrown.
2843 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2844 if (Build.VERSION.SDK_INT >= 21) {
2845 finishAndRemoveTask();
2850 // Remove the terminated program from RAM. The status code is `0`.
2855 // Close the navigation drawer.
2856 drawerLayout.closeDrawer(GravityCompat.START);
2861 public void onPostCreate(Bundle savedInstanceState) {
2862 super.onPostCreate(savedInstanceState);
2864 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2865 drawerToggle.syncState();
2869 public void onConfigurationChanged(Configuration newConfig) {
2870 super.onConfigurationChanged(newConfig);
2872 // Reload the ad for the free flavor if we not in full screen mode.
2873 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2874 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2875 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2878 // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug:
2879 // https://code.google.com/p/android/issues/detail?id=20493#c8
2880 // ActivityCompat.invalidateOptionsMenu(this);
2884 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2885 // Store the `HitTestResult`.
2886 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2889 final String imageUrl;
2890 final String linkUrl;
2892 // Get a handle for the `ClipboardManager`.
2893 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2895 // Remove the lint errors below that `clipboardManager` might be `null`.
2896 assert clipboardManager != null;
2898 switch (hitTestResult.getType()) {
2899 // `SRC_ANCHOR_TYPE` is a link.
2900 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2901 // Get the target URL.
2902 linkUrl = hitTestResult.getExtra();
2904 // Set the target URL as the title of the `ContextMenu`.
2905 menu.setHeaderTitle(linkUrl);
2907 // Add a Load URL entry.
2908 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2913 // Add a Copy URL entry.
2914 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2915 // Save the link URL in a `ClipData`.
2916 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2918 // Set the `ClipData` as the clipboard's primary clip.
2919 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2923 // Add a Download URL entry.
2924 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2925 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2926 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2927 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2929 // Store the variables for future use by `onRequestPermissionsResult()`.
2930 downloadUrl = linkUrl;
2931 downloadContentDisposition = "none";
2932 downloadContentLength = -1;
2934 // Show a dialog if the user has previously denied the permission.
2935 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2936 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2937 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2939 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2940 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2941 } else { // Show the permission request directly.
2942 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2943 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2945 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2946 // Get a handle for the download file alert dialog.
2947 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2949 // Show the download file alert dialog.
2950 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2955 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2956 menu.add(R.string.cancel);
2959 case WebView.HitTestResult.EMAIL_TYPE:
2960 // Get the target URL.
2961 linkUrl = hitTestResult.getExtra();
2963 // Set the target URL as the title of the `ContextMenu`.
2964 menu.setHeaderTitle(linkUrl);
2966 // Add a `Write Email` entry.
2967 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2968 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2969 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2971 // Parse the url and set it as the data for the `Intent`.
2972 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2974 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2975 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2978 startActivity(emailIntent);
2982 // Add a `Copy Email Address` entry.
2983 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2984 // Save the email address in a `ClipData`.
2985 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2987 // Set the `ClipData` as the clipboard's primary clip.
2988 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2992 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2993 menu.add(R.string.cancel);
2996 // `IMAGE_TYPE` is an image.
2997 case WebView.HitTestResult.IMAGE_TYPE:
2998 // Get the image URL.
2999 imageUrl = hitTestResult.getExtra();
3001 // Set the image URL as the title of the `ContextMenu`.
3002 menu.setHeaderTitle(imageUrl);
3004 // Add a `View Image` entry.
3005 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3010 // Add a `Download Image` entry.
3011 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3012 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3013 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3014 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3016 // Store the image URL for use by `onRequestPermissionResult()`.
3017 downloadImageUrl = imageUrl;
3019 // Show a dialog if the user has previously denied the permission.
3020 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3021 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3022 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3024 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3025 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3026 } else { // Show the permission request directly.
3027 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3028 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3030 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3031 // Get a handle for the download image alert dialog.
3032 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3034 // Show the download image alert dialog.
3035 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3040 // Add a `Copy URL` entry.
3041 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3042 // Save the image URL in a `ClipData`.
3043 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3045 // Set the `ClipData` as the clipboard's primary clip.
3046 clipboardManager.setPrimaryClip(srcImageTypeClipData);
3050 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3051 menu.add(R.string.cancel);
3055 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
3056 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
3057 // Get the image URL.
3058 imageUrl = hitTestResult.getExtra();
3060 // Set the image URL as the title of the `ContextMenu`.
3061 menu.setHeaderTitle(imageUrl);
3063 // Add a `View Image` entry.
3064 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3069 // Add a `Download Image` entry.
3070 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3071 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3072 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3073 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3075 // Store the image URL for use by `onRequestPermissionResult()`.
3076 downloadImageUrl = imageUrl;
3078 // Show a dialog if the user has previously denied the permission.
3079 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3080 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3081 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3083 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3084 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3085 } else { // Show the permission request directly.
3086 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3087 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3089 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3090 // Get a handle for the download image alert dialog.
3091 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3093 // Show the download image alert dialog.
3094 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3099 // Add a `Copy URL` entry.
3100 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3101 // Save the image URL in a `ClipData`.
3102 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3104 // Set the `ClipData` as the clipboard's primary clip.
3105 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3109 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3110 menu.add(R.string.cancel);
3116 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3117 // Get the `EditTexts` from the `dialogFragment`.
3118 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3119 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3121 // Extract the strings from the `EditTexts`.
3122 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3123 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3125 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3126 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3127 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3128 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3130 // Display the new bookmark below the current items in the (0 indexed) list.
3131 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3133 // Create the bookmark.
3134 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3136 // Update `bookmarksCursor` with the current contents of this folder.
3137 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3139 // Update the `ListView`.
3140 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3142 // Scroll to the new bookmark.
3143 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3147 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3148 // Get handles for the views in `dialogFragment`.
3149 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3150 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3151 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3153 // Get new folder name string.
3154 String folderNameString = createFolderNameEditText.getText().toString();
3156 // Get the new folder icon `Bitmap`.
3157 Bitmap folderIconBitmap;
3158 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3159 // Get the default folder icon and convert it to a `Bitmap`.
3160 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3161 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3162 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3163 } else { // Use the `WebView` favorite icon.
3164 folderIconBitmap = favoriteIconBitmap;
3167 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3168 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3169 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3170 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3172 // Move all the bookmarks down one in the display order.
3173 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3174 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3175 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3178 // Create the folder, which will be placed at the top of the `ListView`.
3179 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3181 // Update `bookmarksCursor` with the current contents of this folder.
3182 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3184 // Update the `ListView`.
3185 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3187 // Scroll to the new folder.
3188 bookmarksListView.setSelection(0);
3192 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3193 // Get the shortcut name.
3194 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3195 String shortcutNameString = shortcutNameEditText.getText().toString();
3197 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3198 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3200 // Setup the shortcut intent.
3201 Intent shortcutIntent = new Intent();
3202 shortcutIntent.setAction(Intent.ACTION_VIEW);
3203 shortcutIntent.setData(Uri.parse(formattedUrlString));
3205 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3206 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3208 // Add the required fields to the shortcut info builder.
3209 shortcutInfoBuilder.setIcon(favoriteIcon);
3210 shortcutInfoBuilder.setIntent(shortcutIntent);
3211 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3213 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3214 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3218 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3219 switch (downloadType) {
3220 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3221 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3222 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3225 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3226 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3227 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3233 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
3234 switch (requestCode) {
3235 case DOWNLOAD_FILE_REQUEST_CODE:
3236 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3237 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3239 // On API 23, displaying the fragment must be delayed or the app will crash.
3240 if (Build.VERSION.SDK_INT == 23) {
3241 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3243 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3246 // Reset the download variables.
3248 downloadContentDisposition = "";
3249 downloadContentLength = 0;
3252 case DOWNLOAD_IMAGE_REQUEST_CODE:
3253 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3254 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3256 // On API 23, displaying the fragment must be delayed or the app will crash.
3257 if (Build.VERSION.SDK_INT == 23) {
3258 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3260 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3263 // Reset the image URL variable.
3264 downloadImageUrl = "";
3270 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3271 // Download the image if it has an HTTP or HTTPS URI.
3272 if (imageUrl.startsWith("http")) {
3273 // Get a handle for the system `DOWNLOAD_SERVICE`.
3274 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3276 // Parse `imageUrl`.
3277 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3279 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3280 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3281 if (firstPartyCookiesEnabled) {
3282 // Get the cookies for `imageUrl`.
3283 String cookies = cookieManager.getCookie(imageUrl);
3285 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3286 downloadRequest.addRequestHeader("Cookie", cookies);
3289 // Get the file name from the dialog fragment.
3290 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3291 String imageName = downloadImageNameEditText.getText().toString();
3293 // Specify the download location.
3294 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3295 // Download to the public download directory.
3296 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3297 } else { // External write permission denied.
3298 // Download to the app's external download directory.
3299 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3302 // Allow `MediaScanner` to index the download if it is a media file.
3303 downloadRequest.allowScanningByMediaScanner();
3305 // Add the URL as the description for the download.
3306 downloadRequest.setDescription(imageUrl);
3308 // Show the download notification after the download is completed.
3309 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3311 // Remove the lint warning below that `downloadManager` might be `null`.
3312 assert downloadManager != null;
3314 // Initiate the download.
3315 downloadManager.enqueue(downloadRequest);
3316 } else { // The image is not an HTTP or HTTPS URI.
3317 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3322 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3323 // Download the file if it has an HTTP or HTTPS URI.
3324 if (downloadUrl.startsWith("http")) {
3325 // Get a handle for the system `DOWNLOAD_SERVICE`.
3326 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3328 // Parse `downloadUrl`.
3329 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3331 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3332 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3333 if (firstPartyCookiesEnabled) {
3334 // Get the cookies for `downloadUrl`.
3335 String cookies = cookieManager.getCookie(downloadUrl);
3337 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3338 downloadRequest.addRequestHeader("Cookie", cookies);
3341 // Get the file name from the dialog fragment.
3342 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3343 String fileName = downloadFileNameEditText.getText().toString();
3345 // Specify the download location.
3346 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3347 // Download to the public download directory.
3348 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3349 } else { // External write permission denied.
3350 // Download to the app's external download directory.
3351 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3354 // Allow `MediaScanner` to index the download if it is a media file.
3355 downloadRequest.allowScanningByMediaScanner();
3357 // Add the URL as the description for the download.
3358 downloadRequest.setDescription(downloadUrl);
3360 // Show the download notification after the download is completed.
3361 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3363 // Remove the lint warning below that `downloadManager` might be `null`.
3364 assert downloadManager != null;
3366 // Initiate the download.
3367 downloadManager.enqueue(downloadRequest);
3368 } else { // The download is not an HTTP or HTTPS URI.
3369 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3374 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3375 // Get handles for the views from `dialogFragment`.
3376 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3377 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3378 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3380 // Store the bookmark strings.
3381 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3382 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3384 // Update the bookmark.
3385 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3386 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3387 } else { // Update the bookmark using the `WebView` favorite icon.
3388 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3389 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3390 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3391 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3393 // Update the bookmark and the favorite icon.
3394 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3397 // Update `bookmarksCursor` with the current contents of this folder.
3398 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3400 // Update the `ListView`.
3401 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3405 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3406 // Get handles for the views from `dialogFragment`.
3407 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3408 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3409 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3410 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3412 // Get the new folder name.
3413 String newFolderNameString = editFolderNameEditText.getText().toString();
3415 // Check if the favorite icon has changed.
3416 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3417 // Update the name in the database.
3418 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3419 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3420 // Get the new folder icon `Bitmap`.
3421 Bitmap folderIconBitmap;
3422 if (defaultFolderIconRadioButton.isChecked()) {
3423 // Get the default folder icon and convert it to a `Bitmap`.
3424 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3425 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3426 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3427 } else { // Use the `WebView` favorite icon.
3428 folderIconBitmap = favoriteIconBitmap;
3431 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3432 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3433 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3434 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3436 // Update the folder icon in the database.
3437 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3438 } else { // The folder icon and the name have changed.
3439 // Get the new folder icon `Bitmap`.
3440 Bitmap folderIconBitmap;
3441 if (defaultFolderIconRadioButton.isChecked()) {
3442 // Get the default folder icon and convert it to a `Bitmap`.
3443 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3444 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3445 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3446 } else { // Use the `WebView` favorite icon.
3447 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3450 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3451 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3452 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3453 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3455 // Update the folder name and icon in the database.
3456 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3459 // Update `bookmarksCursor` with the current contents of this folder.
3460 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3462 // Update the `ListView`.
3463 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3467 public void onHttpAuthenticationCancel() {
3468 // Cancel the `HttpAuthHandler`.
3469 httpAuthHandler.cancel();
3473 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3474 // Get handles for the `EditTexts`.
3475 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3476 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3478 // Proceed with the HTTP authentication.
3479 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3482 public void viewSslCertificate(View view) {
3483 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3484 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3485 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3489 public void onSslErrorCancel() {
3490 sslErrorHandler.cancel();
3494 public void onSslErrorProceed() {
3495 sslErrorHandler.proceed();
3499 public void onSslMismatchBack() {
3500 if (mainWebView.canGoBack()) { // There is a back page in the history.
3501 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3502 formattedUrlString = "";
3504 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3505 navigatingHistory = true;
3508 mainWebView.goBack();
3509 } else { // There are no pages to go back to.
3510 // Load a blank page
3516 public void onSslMismatchProceed() {
3517 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3518 ignorePinnedSslCertificate = true;
3522 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3523 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3524 formattedUrlString = "";
3526 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3527 navigatingHistory = true;
3529 // Load the history entry.
3530 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3534 public void onClearHistory() {
3535 // Clear the history.
3536 mainWebView.clearHistory();
3539 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3541 public void onBackPressed() {
3542 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3543 // Close the navigation drawer.
3544 drawerLayout.closeDrawer(GravityCompat.START);
3545 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3546 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3547 // close the bookmarks drawer.
3548 drawerLayout.closeDrawer(GravityCompat.END);
3549 } else { // A subfolder is displayed.
3550 // Place the former parent folder in `currentFolder`.
3551 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3553 // Load the new folder.
3554 loadBookmarksFolder();
3557 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3558 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3559 formattedUrlString = "";
3561 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3562 navigatingHistory = true;
3565 mainWebView.goBack();
3566 } else { // There isn't anything to do in Privacy Browser.
3567 // Pass `onBackPressed()` to the system.
3568 super.onBackPressed();
3572 // 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.
3574 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3575 // File uploads only work on API >= 21.
3576 if (Build.VERSION.SDK_INT >= 21) {
3577 // Pass the file to the WebView.
3578 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3582 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3583 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3584 String unformattedUrlString = urlTextBox.getText().toString().trim();
3586 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3587 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3588 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3589 if (!unformattedUrlString.startsWith("http")) {
3590 unformattedUrlString = "http://" + unformattedUrlString;
3593 // Initialize `unformattedUrl`.
3594 URL unformattedUrl = null;
3596 // 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.
3598 unformattedUrl = new URL(unformattedUrlString);
3599 } catch (MalformedURLException e) {
3600 e.printStackTrace();
3603 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3604 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3605 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3606 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3607 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3608 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3611 Uri.Builder formattedUri = new Uri.Builder();
3612 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3614 // Decode `formattedUri` as a `String` in `UTF-8`.
3615 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3616 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3617 // Load a blank string.
3618 formattedUrlString = "";
3619 } else { // Search for the contents of the URL box.
3620 // Sanitize the search input and convert it to a search.
3621 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3623 // Add the base search URL.
3624 formattedUrlString = searchURL + encodedUrlString;
3627 // 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.
3628 urlTextBox.clearFocus();
3631 loadUrl(formattedUrlString);
3634 private void loadUrl(String url) {// Apply any custom domain settings.
3635 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3636 formattedUrlString = url;
3638 // Apply the domain settings.
3639 applyDomainSettings(url, true, false);
3641 // If loading a website, set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3642 urlIsLoading = !url.equals("");
3645 mainWebView.loadUrl(url, customHeaders);
3648 public void findPreviousOnPage(View view) {
3649 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3650 mainWebView.findNext(false);
3653 public void findNextOnPage(View view) {
3654 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3655 mainWebView.findNext(true);
3658 public void closeFindOnPage(View view) {
3659 // Delete the contents of `find_on_page_edittext`.
3660 findOnPageEditText.setText(null);
3662 // Clear the highlighted phrases.
3663 mainWebView.clearMatches();
3665 // Hide the Find on Page `RelativeLayout`.
3666 findOnPageLinearLayout.setVisibility(View.GONE);
3668 // Show the URL app bar.
3669 supportAppBar.setVisibility(View.VISIBLE);
3671 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3672 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3675 private void applyAppSettings() {
3676 // Get a handle for the shared preferences.
3677 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3679 // Store the values from the shared preferences in variables.
3680 String homepageString = sharedPreferences.getString("homepage", "https://searx.me/");
3681 String torHomepageString = sharedPreferences.getString("tor_homepage", "http://ulrn6sryqaifefld.onion/");
3682 String torSearchString = sharedPreferences.getString("tor_search", "http://ulrn6sryqaifefld.onion/?q=");
3683 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3684 String searchString = sharedPreferences.getString("search", "https://searx.me/?q=");
3685 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3686 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3687 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3688 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3689 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3690 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3691 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3692 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3694 // Set the homepage, search, and proxy options.
3695 if (proxyThroughOrbot) { // Set the Tor options.
3696 // Set `torHomepageString` as `homepage`.
3697 homepage = torHomepageString;
3699 // If formattedUrlString is null assign the homepage to it.
3700 if (formattedUrlString == null) {
3701 formattedUrlString = homepage;
3704 // Set the search URL.
3705 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3706 searchURL = torSearchCustomURLString;
3707 } else { // Use the string from the pre-built list.
3708 searchURL = torSearchString;
3711 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3712 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3714 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3716 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3718 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3721 // Display a message to the user if waiting for Orbot.
3722 if (!orbotStatus.equals("ON")) {
3723 // Set `waitingForOrbot`.
3724 waitingForOrbot = true;
3726 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3727 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3729 } else { // Set the non-Tor options.
3730 // Set `homepageString` as `homepage`.
3731 homepage = homepageString;
3733 // If formattedUrlString is null assign the homepage to it.
3734 if (formattedUrlString == null) {
3735 formattedUrlString = homepage;
3738 // Set the search URL.
3739 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3740 searchURL = searchCustomURLString;
3741 } else { // Use the string from the pre-built list.
3742 searchURL = searchString;
3745 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3746 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3748 // Set the default `appBar` background. `this` refers to the context.
3750 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3752 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3755 // Reset `waitingForOrbot.
3756 waitingForOrbot = false;
3759 // Set Do Not Track status.
3760 if (doNotTrackEnabled) {
3761 customHeaders.put("DNT", "1");
3763 customHeaders.remove("DNT");
3766 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3767 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3768 if (hideSystemBarsOnFullscreen) { // Hide everything.
3769 // Remove the translucent navigation setting if it is currently flagged.
3770 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3772 // Remove the translucent status bar overlay.
3773 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3775 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3776 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3778 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3779 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3780 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3782 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3783 } else { // Hide everything except the status and navigation bars.
3784 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3785 rootCoordinatorLayout.setSystemUiVisibility(0);
3787 // Add the translucent status flag if it is unset.
3788 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3790 if (translucentNavigationBarOnFullscreen) {
3791 // Set the navigation bar to be translucent.
3792 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3794 // Set the navigation bar to be black.
3795 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3798 } else { // Privacy Browser is not in full screen browsing mode.
3799 // 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.
3800 inFullScreenBrowsingMode = false;
3802 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3803 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3807 // Show the `BannerAd` in the free flavor.
3808 if (BuildConfig.FLAVOR.contentEquals("free")) {
3809 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3810 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3813 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3814 rootCoordinatorLayout.setSystemUiVisibility(0);
3816 // Remove the translucent navigation bar flag if it is set.
3817 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3819 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3820 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3822 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3823 rootCoordinatorLayout.setFitsSystemWindows(true);
3827 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3828 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3829 @SuppressWarnings("deprecation")
3830 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3831 // Parse the URL into a URI.
3832 Uri uri = Uri.parse(url);
3834 // Extract the domain from `uri`.
3835 String hostName = uri.getHost();
3837 // Initialize `loadingNewDomainName`.
3838 boolean loadingNewDomainName;
3840 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3841 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3842 //noinspection SimplifiableIfStatement
3843 if ((hostName == null) || (currentDomainName == null)) {
3844 loadingNewDomainName = true;
3845 } else { // Determine if `hostName` equals `currentDomainName`.
3846 loadingNewDomainName = !hostName.equals(currentDomainName);
3849 // Strings don't like to be null.
3850 if (hostName == null) {
3854 // 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.
3855 if (loadingNewDomainName) {
3856 // Set the new `hostname` as the `currentDomainName`.
3857 currentDomainName = hostName;
3859 // Reset `ignorePinnedSslCertificate`.
3860 ignorePinnedSslCertificate = false;
3862 // Reset the favorite icon if specified.
3863 if (resetFavoriteIcon) {
3864 favoriteIconBitmap = favoriteIconDefaultBitmap;
3865 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3868 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3869 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3870 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3872 // Get a full cursor from `domainsDatabaseHelper`.
3873 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3875 // Initialize `domainSettingsSet`.
3876 Set<String> domainSettingsSet = new HashSet<>();
3878 // Get the domain name column index.
3879 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3881 // Populate `domainSettingsSet`.
3882 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3883 // Move `domainsCursor` to the current row.
3884 domainNameCursor.moveToPosition(i);
3886 // Store the domain name in `domainSettingsSet`.
3887 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3890 // Close `domainNameCursor.
3891 domainNameCursor.close();
3893 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3894 domainSettingsApplied = false;
3895 String domainNameInDatabase = null;
3897 // Check the hostname.
3898 if (domainSettingsSet.contains(hostName)) {
3899 domainSettingsApplied = true;
3900 domainNameInDatabase = hostName;
3903 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3904 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3905 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3906 // Apply the domain settings.
3907 domainSettingsApplied = true;
3909 // Store the applied domain names as it appears in the database.
3910 domainNameInDatabase = "*." + hostName;
3913 // Strip out the lowest subdomain of of the host name.
3914 hostName = hostName.substring(hostName.indexOf(".") + 1);
3918 // Get a handle for the shared preference.
3919 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3921 // Store the general preference information.
3922 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3923 String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3924 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3925 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3926 nightMode = sharedPreferences.getBoolean("night_mode", false);
3928 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3929 // Get a cursor for the current host and move it to the first position.
3930 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3931 currentHostDomainSettingsCursor.moveToFirst();
3933 // Get the settings from the cursor.
3934 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3935 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3936 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3937 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3938 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3939 // Form data can be removed once the minimum API >= 26.
3940 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3941 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3942 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3943 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3944 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3945 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3946 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3947 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3948 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3949 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3950 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3951 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3952 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3953 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3954 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3955 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3956 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3957 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3958 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3960 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3961 switch (nightModeInt) {
3962 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3966 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3971 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3973 javaScriptEnabled = true;
3976 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3977 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3978 pinnedDomainSslStartDate = null;
3980 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3983 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3984 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3985 pinnedDomainSslEndDate = null;
3987 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3990 // Close `currentHostDomainSettingsCursor`.
3991 currentHostDomainSettingsCursor.close();
3993 // Apply the domain settings.
3994 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3995 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3996 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3998 // Apply the form data setting if the API < 26.
3999 if (Build.VERSION.SDK_INT < 26) {
4000 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4003 // Apply the font size.
4004 if (fontSize == 0) { // Apply the default font size.
4005 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4006 } else { // Apply the specified font size.
4007 mainWebView.getSettings().setTextZoom(fontSize);
4010 // Set third-party cookies status if API >= 21.
4011 if (Build.VERSION.SDK_INT >= 21) {
4012 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4015 // 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.
4016 // <https://redmine.stoutner.com/issues/160>
4017 if (!urlIsLoading) {
4018 // Set the user agent.
4019 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4020 // Get the array position of the default user agent name.
4021 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4023 // Set the user agent according to the system default.
4024 switch (defaultUserAgentArrayPosition) {
4025 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4026 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4027 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4030 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4031 // Set the user agent to `""`, which uses the default value.
4032 mainWebView.getSettings().setUserAgentString("");
4035 case SETTINGS_CUSTOM_USER_AGENT:
4036 // Set the custom user agent.
4037 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4041 // Get the user agent string from the user agent data array
4042 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4044 } else { // Set the user agent according to the stored name.
4045 // Get the array position of the user agent name.
4046 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4048 switch (userAgentArrayPosition) {
4049 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4050 mainWebView.getSettings().setUserAgentString(userAgentName);
4053 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4054 // Set the user agent to `""`, which uses the default value.
4055 mainWebView.getSettings().setUserAgentString("");
4059 // Get the user agent string from the user agent data array.
4060 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4064 // Set swipe to refresh.
4065 switch (swipeToRefreshInt) {
4066 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
4067 // Set swipe to refresh according to the default.
4068 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4071 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
4072 // Enable swipe to refresh.
4073 swipeRefreshLayout.setEnabled(true);
4076 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
4077 // Disable swipe to refresh.
4078 swipeRefreshLayout.setEnabled(false);
4081 // Store the applied user agent string, which is used in the View Source activity.
4082 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4085 // 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.
4087 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4089 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4091 } else { // The new URL does not have custom domain settings. Load the defaults.
4092 // Store the values from `sharedPreferences` in variables.
4093 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
4094 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
4095 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
4096 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
4097 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false); // Form data can be removed once the minimum API >= 26.
4098 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
4099 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
4100 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
4101 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
4102 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
4103 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
4105 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4107 javaScriptEnabled = true;
4110 // Apply the default settings.
4111 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4112 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4113 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4114 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4115 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4117 // Apply the form data setting if the API < 26.
4118 if (Build.VERSION.SDK_INT < 26) {
4119 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4122 // Reset the pinned SSL certificate information.
4123 domainSettingsDatabaseId = -1;
4124 pinnedDomainSslCertificate = false;
4125 pinnedDomainSslIssuedToCNameString = "";
4126 pinnedDomainSslIssuedToONameString = "";
4127 pinnedDomainSslIssuedToUNameString = "";
4128 pinnedDomainSslIssuedByCNameString = "";
4129 pinnedDomainSslIssuedByONameString = "";
4130 pinnedDomainSslIssuedByUNameString = "";
4131 pinnedDomainSslStartDate = null;
4132 pinnedDomainSslEndDate = null;
4134 // Set third-party cookies status if API >= 21.
4135 if (Build.VERSION.SDK_INT >= 21) {
4136 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4139 // 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.
4140 // <https://redmine.stoutner.com/issues/160>
4141 if (!urlIsLoading) {
4142 // Get the array position of the user agent name.
4143 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4145 // Set the user agent.
4146 switch (userAgentArrayPosition) {
4147 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4148 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4149 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4152 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4153 // Set the user agent to `""`, which uses the default value.
4154 mainWebView.getSettings().setUserAgentString("");
4157 case SETTINGS_CUSTOM_USER_AGENT:
4158 // Set the custom user agent.
4159 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4163 // Get the user agent string from the user agent data array
4164 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4167 // Store the applied user agent string, which is used in the View Source activity.
4168 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4171 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4172 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4175 // Close `domainsDatabaseHelper`.
4176 domainsDatabaseHelper.close();
4178 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
4179 onTheFlyDisplayImagesSet = false;
4180 setDisplayWebpageImages();
4182 // Update the privacy icons, but only if `mainMenu` has already been populated.
4183 if (mainMenu != null) {
4184 updatePrivacyIcons(true);
4188 // Reload the website if returning from the Domains activity.
4189 if (reloadWebsite) {
4190 mainWebView.reload();
4194 private void setDisplayWebpageImages() {
4195 if (!onTheFlyDisplayImagesSet) {
4196 if (domainSettingsApplied) { // Custom domain settings are applied.
4197 switch (displayWebpageImagesInt) {
4198 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4199 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4202 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4203 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4206 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4207 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4210 } else { // Default settings are applied.
4211 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4216 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4217 // Get handles for the menu items.
4218 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4219 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4220 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4221 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4223 // Update the privacy icon.
4224 if (javaScriptEnabled) { // JavaScript is enabled.
4225 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4226 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4227 privacyMenuItem.setIcon(R.drawable.warning);
4228 } else { // All the dangerous features are disabled.
4229 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4232 // Update the first-party cookies icon.
4233 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4234 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4235 } else { // First-party cookies are disabled.
4237 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4239 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4243 // Update the DOM storage icon.
4244 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4245 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4246 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4248 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4250 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4252 } else { // JavaScript is disabled, so DOM storage is ghosted.
4254 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4256 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4260 // Update the refresh icon.
4262 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4264 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4267 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4268 if (runInvalidateOptionsMenu) {
4269 invalidateOptionsMenu();
4273 private void highlightUrlText() {
4274 String urlString = urlTextBox.getText().toString();
4276 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4277 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4278 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4279 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4282 // Get the index of the `/` immediately after the domain name.
4283 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4285 // De-emphasize the text after the domain name.
4286 if (endOfDomainName > 0) {
4287 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4291 private void loadBookmarksFolder() {
4292 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4293 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4295 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4296 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4298 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4299 // Inflate the individual item layout. `false` does not attach it to the root.
4300 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4304 public void bindView(View view, Context context, Cursor cursor) {
4305 // Get handles for the views.
4306 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4307 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4309 // Get the favorite icon byte array from the cursor.
4310 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4312 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4313 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4315 // Display the bitmap in `bookmarkFavoriteIcon`.
4316 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4318 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4319 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4320 bookmarkNameTextView.setText(bookmarkNameString);
4322 // Make the font bold for folders.
4323 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4324 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4325 } else { // Reset the font to default for normal bookmarks.
4326 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4331 // Populate the `ListView` with the adapter.
4332 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4334 // Set the bookmarks drawer title.
4335 if (currentBookmarksFolder.isEmpty()) {
4336 bookmarksTitleTextView.setText(R.string.bookmarks);
4338 bookmarksTitleTextView.setText(currentBookmarksFolder);