2 * Copyright © 2015-2018 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.Activity;
27 import android.app.DialogFragment;
28 import android.app.DownloadManager;
29 import android.content.ActivityNotFoundException;
30 import android.content.BroadcastReceiver;
31 import android.content.ClipData;
32 import android.content.ClipboardManager;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.SharedPreferences;
37 import android.content.pm.PackageManager;
38 import android.content.res.Configuration;
39 import android.database.Cursor;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Typeface;
43 import android.graphics.drawable.BitmapDrawable;
44 import android.graphics.drawable.Drawable;
45 import android.net.Uri;
46 import android.net.http.SslCertificate;
47 import android.net.http.SslError;
48 import android.os.Build;
49 import android.os.Bundle;
50 import android.os.Environment;
51 import android.os.Handler;
52 import android.preference.PreferenceManager;
53 import android.print.PrintDocumentAdapter;
54 import android.print.PrintManager;
55 import android.support.annotation.NonNull;
56 import android.support.design.widget.CoordinatorLayout;
57 import android.support.design.widget.FloatingActionButton;
58 import android.support.design.widget.NavigationView;
59 import android.support.design.widget.Snackbar;
60 import android.support.v4.app.ActivityCompat;
61 import android.support.v4.content.ContextCompat;
62 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
63 import android.support.v4.content.pm.ShortcutInfoCompat;
64 import android.support.v4.content.pm.ShortcutManagerCompat;
65 import android.support.v4.graphics.drawable.IconCompat;
66 import android.support.v4.view.GravityCompat;
67 import android.support.v4.widget.DrawerLayout;
68 import android.support.v4.widget.SwipeRefreshLayout;
69 import android.support.v7.app.ActionBar;
70 import android.support.v7.app.ActionBarDrawerToggle;
71 import android.support.v7.app.AppCompatActivity;
72 import android.support.v7.app.AppCompatDialogFragment;
73 import android.support.v7.widget.Toolbar;
74 import android.text.Editable;
75 import android.text.Spanned;
76 import android.text.TextWatcher;
77 import android.text.style.ForegroundColorSpan;
78 import android.util.Patterns;
79 import android.view.ContextMenu;
80 import android.view.GestureDetector;
81 import android.view.KeyEvent;
82 import android.view.Menu;
83 import android.view.MenuItem;
84 import android.view.MotionEvent;
85 import android.view.View;
86 import android.view.ViewGroup;
87 import android.view.WindowManager;
88 import android.view.inputmethod.InputMethodManager;
89 import android.webkit.CookieManager;
90 import android.webkit.HttpAuthHandler;
91 import android.webkit.SslErrorHandler;
92 import android.webkit.ValueCallback;
93 import android.webkit.WebBackForwardList;
94 import android.webkit.WebChromeClient;
95 import android.webkit.WebResourceResponse;
96 import android.webkit.WebStorage;
97 import android.webkit.WebView;
98 import android.webkit.WebViewClient;
99 import android.webkit.WebViewDatabase;
100 import android.widget.ArrayAdapter;
101 import android.widget.CursorAdapter;
102 import android.widget.EditText;
103 import android.widget.FrameLayout;
104 import android.widget.ImageView;
105 import android.widget.LinearLayout;
106 import android.widget.ListView;
107 import android.widget.ProgressBar;
108 import android.widget.RadioButton;
109 import android.widget.RelativeLayout;
110 import android.widget.TextView;
112 import com.stoutner.privacybrowser.BuildConfig;
113 import com.stoutner.privacybrowser.R;
114 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
116 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
117 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
118 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
119 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
120 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
121 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
122 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
123 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
124 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
125 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
126 import com.stoutner.privacybrowser.helpers.AdHelper;
127 import com.stoutner.privacybrowser.helpers.BlockListHelper;
128 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
129 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
130 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
131 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
132 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
134 import java.io.ByteArrayInputStream;
135 import java.io.ByteArrayOutputStream;
137 import java.io.IOException;
138 import java.io.UnsupportedEncodingException;
139 import java.net.MalformedURLException;
141 import java.net.URLDecoder;
142 import java.net.URLEncoder;
143 import java.util.ArrayList;
144 import java.util.Date;
145 import java.util.HashMap;
146 import java.util.HashSet;
147 import java.util.List;
148 import java.util.Map;
149 import java.util.Set;
151 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
152 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
153 CreateHomeScreenShortcutDialog.CreateHomeScreenShortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
154 DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
155 HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
156 SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
158 // `darkTheme` is public static so it can be accessed from everywhere.
159 public static boolean darkTheme;
161 // `allowScreenshots` is public static so it can be accessed from everywhere. It is also used in `onCreate()`.
162 public static boolean allowScreenshots;
164 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
165 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
166 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
167 public static Bitmap favoriteIconBitmap;
169 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
170 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
171 public static String formattedUrlString;
173 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
174 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
175 public static SslCertificate sslCertificate;
177 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()` and `onResume()`.
178 public static String orbotStatus;
180 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
181 public static String webViewTitle;
183 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
184 public static String appliedUserAgentString;
186 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
187 public static boolean reloadOnRestart;
189 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`. It is also used in `onRestart()`.
190 public static boolean loadUrlOnRestart;
192 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
193 public static boolean restartFromBookmarksActivity;
195 // The block list versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
196 public static String easyListVersion;
197 public static String easyPrivacyVersion;
198 public static String fanboysAnnoyanceVersion;
199 public static String fanboysSocialVersion;
200 public static String ultraPrivacyVersion;
202 // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`. They are also used in `onCreate()` and `onPrepareOptionsMenu()`.
203 public static List<String[]> resourceRequests;
204 public static String[] whiteListResultStringArray;
206 int easyListBlockedRequests;
207 int easyPrivacyBlockedRequests;
208 int fanboysAnnoyanceListBlockedRequests;
209 int fanboysSocialBlockingListBlockedRequests;
210 int ultraPrivacyBlockedRequests;
211 int thirdPartyBlockedRequests;
213 public final static int REQUEST_DISPOSITION = 0;
214 public final static int REQUEST_URL = 1;
215 public final static int REQUEST_BLOCKLIST = 2;
216 public final static int REQUEST_SUBLIST = 3;
217 public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
218 public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
220 public final static int REQUEST_DEFAULT = 0;
221 public final static int REQUEST_ALLOWED = 1;
222 public final static int REQUEST_THIRD_PARTY = 2;
223 public final static int REQUEST_BLOCKED = 3;
225 public final static int MAIN_WHITELIST = 1;
226 public final static int FINAL_WHITELIST = 2;
227 public final static int DOMAIN_WHITELIST = 3;
228 public final static int DOMAIN_INITIAL_WHITELIST = 4;
229 public final static int DOMAIN_FINAL_WHITELIST = 5;
230 public final static int THIRD_PARTY_WHITELIST = 6;
231 public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
232 public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
234 public final static int MAIN_BLACKLIST = 9;
235 public final static int INITIAL_BLACKLIST = 10;
236 public final static int FINAL_BLACKLIST = 11;
237 public final static int DOMAIN_BLACKLIST = 12;
238 public final static int DOMAIN_INITIAL_BLACKLIST = 13;
239 public final static int DOMAIN_FINAL_BLACKLIST = 14;
240 public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
241 public final static int THIRD_PARTY_BLACKLIST = 16;
242 public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
243 public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
244 public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
245 public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
246 public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
247 public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
249 // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
250 // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
251 public static boolean blockAllThirdPartyRequests;
253 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
254 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
255 public static String currentBookmarksFolder;
257 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
258 public static int domainSettingsDatabaseId;
260 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
261 public static String pinnedDomainSslIssuedToCNameString;
262 public static String pinnedDomainSslIssuedToONameString;
263 public static String pinnedDomainSslIssuedToUNameString;
264 public static String pinnedDomainSslIssuedByCNameString;
265 public static String pinnedDomainSslIssuedByONameString;
266 public static String pinnedDomainSslIssuedByUNameString;
267 public static Date pinnedDomainSslStartDate;
268 public static Date pinnedDomainSslEndDate;
270 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
271 public final static int UNRECOGNIZED_USER_AGENT = -1;
272 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
273 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
274 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
275 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
276 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
279 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
280 private ActionBar appBar;
282 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
283 private boolean navigatingHistory;
285 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
286 private Bitmap favoriteIconDefaultBitmap;
288 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
289 private DrawerLayout drawerLayout;
291 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
292 private CoordinatorLayout rootCoordinatorLayout;
294 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
295 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
296 private WebView mainWebView;
298 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
299 private FrameLayout fullScreenVideoFrameLayout;
301 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
302 private SwipeRefreshLayout swipeRefreshLayout;
304 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
305 private RelativeLayout urlAppBarRelativeLayout;
307 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
308 private ImageView favoriteIconImageView;
310 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
311 private CookieManager cookieManager;
313 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
314 private final Map<String, String> customHeaders = new HashMap<>();
316 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
317 private boolean javaScriptEnabled;
319 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
320 private boolean firstPartyCookiesEnabled;
322 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
323 private boolean thirdPartyCookiesEnabled;
325 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
326 private boolean domStorageEnabled;
328 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`. It can be removed once the minimum API >= 26.
329 private boolean saveFormDataEnabled;
331 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
332 private boolean nightMode;
334 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
335 private boolean displayWebpageImagesBoolean;
337 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
338 private String homepage;
340 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
341 private String searchURL;
343 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
344 private Menu mainMenu;
346 // `refreshMenuItem` is used in `onCreate()` and `onCreateOptionsMenu()`.
347 private MenuItem refreshMenuItem;
349 // The blocklist menu items are used in `onCreate()`, `onCreateOptionsMenu()`, and `onPrepareOptionsMenu()`.
350 private MenuItem blocklistsMenuItem;
351 private MenuItem easyListMenuItem;
352 private MenuItem easyPrivacyMenuItem;
353 private MenuItem fanboysAnnoyanceListMenuItem;
354 private MenuItem fanboysSocialBlockingListMenuItem;
355 private MenuItem ultraPrivacyMenuItem;
356 private MenuItem blockAllThirdParyRequestsMenuItem;
358 // The blocklist variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
359 private boolean easyListEnabled;
360 private boolean easyPrivacyEnabled;
361 private boolean fanboysAnnoyanceListEnabled;
362 private boolean fanboysSocialBlockingListEnabled;
363 private boolean ultraPrivacyEnabled;
365 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
366 private String webViewDefaultUserAgent;
368 // `defaultCustomUserAgentString` is used in `onPrepareOptionsMenu()` and `applyDomainSettings()`.
369 private String defaultCustomUserAgentString;
371 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
372 private Runtime privacyBrowserRuntime;
374 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
375 private boolean proxyThroughOrbot;
377 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
378 private boolean incognitoModeEnabled;
380 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
381 private boolean fullScreenBrowsingModeEnabled;
383 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
384 private boolean inFullScreenBrowsingMode;
386 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
387 private boolean hideSystemBarsOnFullscreen;
389 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
390 private boolean translucentNavigationBarOnFullscreen;
392 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
393 private boolean reapplyDomainSettingsOnRestart;
395 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
396 private boolean reapplyAppSettingsOnRestart;
398 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
399 private boolean displayingFullScreenVideo;
401 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
402 private String currentDomainName;
404 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
405 private boolean ignorePinnedSslCertificate;
407 // `orbotStatusBroadcastReciever` is used in `onCreate()` and `onDestroy()`.
408 private BroadcastReceiver orbotStatusBroadcastReceiver;
410 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyAppSettings()`.
411 private boolean waitingForOrbot;
413 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
414 private boolean domainSettingsApplied;
416 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
417 private int displayWebpageImagesInt;
419 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
420 private boolean onTheFlyDisplayImagesSet;
422 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
423 private String waitingForOrbotHTMLString;
425 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
426 private String privateDataDirectoryString;
428 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
429 private LinearLayout findOnPageLinearLayout;
431 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
432 private EditText findOnPageEditText;
434 // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
435 private boolean displayAdditionalAppBarIcons;
437 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
438 private ActionBarDrawerToggle drawerToggle;
440 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
441 private Toolbar supportAppBar;
443 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
444 private EditText urlTextBox;
446 // The color spans are used in `onCreate()` and `highlightUrlText()`.
447 private ForegroundColorSpan redColorSpan;
448 private ForegroundColorSpan initialGrayColorSpan;
449 private ForegroundColorSpan finalGrayColorSpan;
451 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
452 private SslErrorHandler sslErrorHandler;
454 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
455 private static HttpAuthHandler httpAuthHandler;
457 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
458 private InputMethodManager inputMethodManager;
460 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
461 private RelativeLayout mainWebViewRelativeLayout;
463 // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
464 private boolean urlIsLoading;
466 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
467 private boolean pinnedDomainSslCertificate;
469 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
470 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
472 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
473 private ListView bookmarksListView;
475 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
476 private TextView bookmarksTitleTextView;
478 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
479 private Cursor bookmarksCursor;
481 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
482 private CursorAdapter bookmarksCursorAdapter;
484 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
485 private String oldFolderNameString;
487 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
488 private ValueCallback<Uri[]> fileChooserCallback;
490 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
491 private String downloadUrl;
492 private String downloadContentDisposition;
493 private long downloadContentLength;
495 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
496 private String downloadImageUrl;
498 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
499 private ArrayAdapter<CharSequence> userAgentNamesArray;
500 private String[] userAgentDataArray;
502 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
503 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
504 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
507 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled. The whole premise of Privacy Browser is built around an understanding of these dangers.
508 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
509 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
510 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
511 @SuppressWarnings("deprecation")
512 protected void onCreate(Bundle savedInstanceState) {
513 // Get a handle for the shared preferences.
514 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
516 // Get the theme and screenshot preferences.
517 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
518 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
520 // Disable screenshots if not allowed.
521 if (!allowScreenshots) {
522 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
525 // Set the activity theme.
527 setTheme(R.style.PrivacyBrowserDark);
529 setTheme(R.style.PrivacyBrowserLight);
532 // Run the default commands.
533 super.onCreate(savedInstanceState);
535 // Set the content view.
536 setContentView(R.layout.main_drawerlayout);
538 // Get a handle for `inputMethodManager`.
539 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
541 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
542 supportAppBar = findViewById(R.id.app_bar);
543 setSupportActionBar(supportAppBar);
544 appBar = getSupportActionBar();
546 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
547 assert appBar != null;
549 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
550 appBar.setCustomView(R.layout.url_app_bar);
551 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
553 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
554 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
555 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
556 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
558 // Get a handle for `urlTextBox`.
559 urlTextBox = findViewById(R.id.url_edittext);
561 // Remove the formatting from `urlTextBar` when the user is editing the text.
562 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
563 if (hasFocus) { // The user is editing `urlTextBox`.
564 // Remove the highlighting.
565 urlTextBox.getText().removeSpan(redColorSpan);
566 urlTextBox.getText().removeSpan(initialGrayColorSpan);
567 urlTextBox.getText().removeSpan(finalGrayColorSpan);
568 } else { // The user has stopped editing `urlTextBox`.
569 // Reapply the highlighting.
574 // Set the go button on the keyboard to load the URL in `urlTextBox`.
575 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
576 // If the event is a key-down event on the `enter` button, load the URL.
577 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
578 // Load the URL into the mainWebView and consume the event.
580 loadUrlFromTextBox();
581 } catch (UnsupportedEncodingException e) {
584 // If the enter key was pressed, consume the event.
587 // If any other key was pressed, do not consume the event.
592 // Set `waitingForOrbotHTMLString`.
593 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
595 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
596 currentDomainName = "";
597 orbotStatus = "unknown";
598 waitingForOrbot = false;
600 // Create an Orbot status `BroadcastReceiver`.
601 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
603 public void onReceive(Context context, Intent intent) {
604 // Store the content of the status message in `orbotStatus`.
605 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
607 // If we are waiting on Orbot, load the website now that Orbot is connected.
608 if (orbotStatus.equals("ON") && waitingForOrbot) {
609 // Reset `waitingForOrbot`.
610 waitingForOrbot = false;
612 // Load `formattedUrlString
613 loadUrl(formattedUrlString);
618 // Register `orbotStatusBroadcastReceiver` on `this` context.
619 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
621 // Get handles for views that need to be accessed.
622 drawerLayout = findViewById(R.id.drawerlayout);
623 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
624 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
625 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
626 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
627 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
628 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
629 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
630 mainWebView = findViewById(R.id.main_webview);
631 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
632 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
633 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
634 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
635 favoriteIconImageView = findViewById(R.id.favorite_icon);
637 // Set the bookmarks drawer resources according to the theme. This can't be done in the layout due to compatibility issues with the `DrawerLayout` support widget.
639 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
640 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
641 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
642 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
644 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
645 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
646 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
647 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
650 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
651 launchBookmarksActivityFab.setOnClickListener(v -> {
652 // Create an intent to launch the bookmarks activity.
653 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
655 // Include the current folder with the `Intent`.
656 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
659 startActivity(bookmarksIntent);
662 // Set the create new bookmark folder FAB to display an alert dialog.
663 createBookmarkFolderFab.setOnClickListener(v -> {
664 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
665 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
666 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
669 // Set the create new bookmark FAB to display an alert dialog.
670 createBookmarkFab.setOnClickListener(view -> {
671 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
672 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
673 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
676 // Create a double-tap listener to toggle full-screen mode.
677 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
678 // Override `onDoubleTap()`. All other events are handled using the default settings.
680 public boolean onDoubleTap(MotionEvent event) {
681 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
682 // Toggle `inFullScreenBrowsingMode`.
683 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
685 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
686 // Hide the `appBar`.
689 // Hide the banner ad in the free flavor.
690 if (BuildConfig.FLAVOR.contentEquals("free")) {
691 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
692 AdHelper.hideAd(findViewById(R.id.adview));
695 // Modify the system bars.
696 if (hideSystemBarsOnFullscreen) { // Hide everything.
697 // Remove the translucent overlays.
698 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
700 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
701 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
703 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
704 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
705 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
707 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
709 // Set `rootCoordinatorLayout` to fill the whole screen.
710 rootCoordinatorLayout.setFitsSystemWindows(false);
711 } else { // Hide everything except the status and navigation bars.
712 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
713 rootCoordinatorLayout.setFitsSystemWindows(false);
715 // There is an Android Support Library bug that causes a scrim to print on the right side of the `Drawer Layout` when the navigation bar is displayed on the right of the screen.
716 if (translucentNavigationBarOnFullscreen) {
717 // Set the navigation bar to be translucent.
718 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
721 } else { // Switch to normal viewing mode.
722 // Show the `appBar`.
725 // Show the `BannerAd` in the free flavor.
726 if (BuildConfig.FLAVOR.contentEquals("free")) {
727 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
728 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
731 // Remove the translucent navigation bar flag if it is set.
732 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
734 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
735 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
737 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
738 rootCoordinatorLayout.setSystemUiVisibility(0);
740 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
741 rootCoordinatorLayout.setFitsSystemWindows(true);
744 // Consume the double-tap.
746 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
752 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
753 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
754 // Call `performClick()` on the view, which is required for accessibility.
757 // Send the `event` to `gestureDetector`.
758 return gestureDetector.onTouchEvent(event);
761 // Update `findOnPageCountTextView`.
762 mainWebView.setFindListener(new WebView.FindListener() {
763 // Get a handle for `findOnPageCountTextView`.
764 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
767 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
768 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
769 // Set `findOnPageCountTextView` to `0/0`.
770 findOnPageCountTextView.setText(R.string.zero_of_zero);
771 } else if (isDoneCounting) { // There are matches.
772 // `activeMatchOrdinal` is zero-based.
773 int activeMatch = activeMatchOrdinal + 1;
775 // Build the match string.
776 String matchString = activeMatch + "/" + numberOfMatches;
778 // Set `findOnPageCountTextView`.
779 findOnPageCountTextView.setText(matchString);
784 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
785 findOnPageEditText.addTextChangedListener(new TextWatcher() {
787 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
792 public void onTextChanged(CharSequence s, int start, int before, int count) {
797 public void afterTextChanged(Editable s) {
798 // Search for the text in `mainWebView`.
799 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
803 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
804 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
805 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
806 // Hide the soft keyboard. `0` indicates no additional flags.
807 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
809 // Consume the event.
811 } else { // A different key was pressed.
812 // Do not consume the event.
817 // Implement swipe to refresh
818 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
819 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
820 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
822 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
823 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
824 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
826 // Listen for touches on the navigation menu.
827 final NavigationView navigationView = findViewById(R.id.navigationview);
828 navigationView.setNavigationItemSelectedListener(this);
830 // Get handles for `navigationMenu` and the back and forward menu items. The menu is zero-based, so items 1, 2, and 3 are the second, third, and fourth entries in the menu.
831 final Menu navigationMenu = navigationView.getMenu();
832 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
833 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
834 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
835 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
837 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
838 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
839 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
841 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
842 currentBookmarksFolder = "";
844 // Load the home folder, which is `""` in the database.
845 loadBookmarksFolder();
847 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
848 // Convert the id from long to int to match the format of the bookmarks database.
849 int databaseID = (int) id;
851 // Get the bookmark cursor for this ID and move it to the first row.
852 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
853 bookmarkCursor.moveToFirst();
855 // Act upon the bookmark according to the type.
856 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
857 // Store the new folder name in `currentBookmarksFolder`.
858 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
860 // Load the new folder.
861 loadBookmarksFolder();
862 } else { // The selected bookmark is not a folder.
863 // Load the bookmark URL.
864 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
866 // Close the bookmarks drawer.
867 drawerLayout.closeDrawer(GravityCompat.END);
870 // Close the `Cursor`.
871 bookmarkCursor.close();
874 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
875 // Convert the database ID from `long` to `int`.
876 int databaseId = (int) id;
878 // Find out if the selected bookmark is a folder.
879 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
882 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
883 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
885 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
886 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
887 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
889 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
890 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
891 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
894 // Consume the event.
898 // The drawer listener is used to update the navigation menu.
899 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
901 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
905 public void onDrawerOpened(@NonNull View drawerView) {
909 public void onDrawerClosed(@NonNull View drawerView) {
913 public void onDrawerStateChanged(int newState) {
914 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
915 // Update the back, forward, history, and requests menu items.
916 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
917 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
918 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
919 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
921 // Hide the keyboard (if displayed).
922 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
924 // Clear the focus from from the URL text box.
925 urlTextBox.clearFocus();
930 // drawerToggle creates the hamburger icon at the start of the AppBar.
931 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
933 // Get a handle for the progress bar.
934 final ProgressBar progressBar = findViewById(R.id.progress_bar);
936 mainWebView.setWebChromeClient(new WebChromeClient() {
937 // Update the progress bar when a page is loading.
939 public void onProgressChanged(WebView view, int progress) {
940 // Inject the night mode CSS if night mode is enabled.
942 // `background-color: #212121` sets the background to be dark gray. `color: #BDBDBD` sets the text color to be light gray. `box-shadow: none` removes a lower underline on links
943 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
944 // `border: none` removes all borders, which can also be used to underline text.
945 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
946 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
947 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
948 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
949 // Initialize a `Handler` to display `mainWebView`.
950 Handler displayWebViewHandler = new Handler();
952 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
953 Runnable displayWebViewRunnable = () -> {
954 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
955 if (progressBar.getVisibility() == View.GONE) {
956 mainWebView.setVisibility(View.VISIBLE);
960 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
961 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
965 // Update the progress bar.
966 progressBar.setProgress(progress);
968 // Set the visibility of the progress bar.
969 if (progress < 100) {
970 // Show the progress bar.
971 progressBar.setVisibility(View.VISIBLE);
973 // Hide the progress bar.
974 progressBar.setVisibility(View.GONE);
976 // Display `mainWebView` if night mode is disabled.
977 // Because of a race condition between `applyDomainSettings` and `onPageStarted`, when night mode is set by domain settings the `WebView` may be hidden even if night mode is not
978 // currently enabled.
980 mainWebView.setVisibility(View.VISIBLE);
983 //Stop the swipe to refresh indicator if it is running
984 swipeRefreshLayout.setRefreshing(false);
988 // Set the favorite icon when it changes.
990 public void onReceivedIcon(WebView view, Bitmap icon) {
991 // Only update the favorite icon if the website has finished loading.
992 if (progressBar.getVisibility() == View.GONE) {
993 // Save a copy of the favorite icon.
994 favoriteIconBitmap = icon;
996 // Place the favorite icon in the appBar.
997 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1001 // Save a copy of the title when it changes.
1003 public void onReceivedTitle(WebView view, String title) {
1004 // Save a copy of the title.
1005 webViewTitle = title;
1008 // Enter full screen video.
1010 public void onShowCustomView(View view, CustomViewCallback callback) {
1011 // Set the full screen video flag.
1012 displayingFullScreenVideo = true;
1014 // Pause the ad if this is the free flavor.
1015 if (BuildConfig.FLAVOR.contentEquals("free")) {
1016 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1017 AdHelper.pauseAd(findViewById(R.id.adview));
1020 // Remove the translucent overlays.
1021 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1023 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1024 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1026 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1027 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1028 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1030 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1032 // Set `rootCoordinatorLayout` to fill the entire screen.
1033 rootCoordinatorLayout.setFitsSystemWindows(false);
1035 // Disable the sliding drawers.
1036 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1038 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1039 fullScreenVideoFrameLayout.addView(view);
1040 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1043 // Exit full screen video.
1045 public void onHideCustomView() {
1046 // Unset the full screen video flag.
1047 displayingFullScreenVideo = false;
1049 // Hide `fullScreenVideoFrameLayout`.
1050 fullScreenVideoFrameLayout.removeAllViews();
1051 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1053 // Enable the sliding drawers.
1054 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1056 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1057 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1058 if (hideSystemBarsOnFullscreen) { // Hide everything.
1059 // Remove the translucent navigation setting if it is currently flagged.
1060 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1062 // Remove the translucent status bar overlay.
1063 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1065 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1066 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1068 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1069 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1070 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1072 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1073 } else { // Hide everything except the status and navigation bars.
1074 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1075 rootCoordinatorLayout.setSystemUiVisibility(0);
1077 // Add the translucent status flag if it is unset.
1078 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1080 if (translucentNavigationBarOnFullscreen) {
1081 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1082 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1084 // Set the navigation bar to be black.
1085 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1088 } else { // Switch to normal viewing mode.
1089 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1090 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1094 // Show the `BannerAd` in the free flavor.
1095 if (BuildConfig.FLAVOR.contentEquals("free")) {
1096 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1097 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1100 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1101 rootCoordinatorLayout.setSystemUiVisibility(0);
1103 // Remove the translucent navigation bar flag if it is set.
1104 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1106 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1107 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1109 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1110 rootCoordinatorLayout.setFitsSystemWindows(true);
1113 // Show the ad if this is the free flavor.
1114 if (BuildConfig.FLAVOR.contentEquals("free")) {
1115 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1116 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1122 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1123 // Show the file chooser if the device is running API >= 21.
1124 if (Build.VERSION.SDK_INT >= 21) {
1125 // Store the file path callback.
1126 fileChooserCallback = filePathCallback;
1128 // Create an intent to open a chooser based ont the file chooser parameters.
1129 Intent fileChooserIntent = fileChooserParams.createIntent();
1131 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1132 startActivityForResult(fileChooserIntent, 0);
1138 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1139 registerForContextMenu(mainWebView);
1141 // Allow the downloading of files.
1142 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1143 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1144 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1145 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1147 // Store the variables for future use by `onRequestPermissionsResult()`.
1149 downloadContentDisposition = contentDisposition;
1150 downloadContentLength = contentLength;
1152 // Show a dialog if the user has previously denied the permission.
1153 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1154 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1155 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1157 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1158 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1159 } else { // Show the permission request directly.
1160 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1161 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1163 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1164 // Get a handle for the download file alert dialog.
1165 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1167 // Show the download file alert dialog.
1168 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1172 // Allow pinch to zoom.
1173 mainWebView.getSettings().setBuiltInZoomControls(true);
1175 // Hide zoom controls.
1176 mainWebView.getSettings().setDisplayZoomControls(false);
1178 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1179 mainWebView.getSettings().setUseWideViewPort(true);
1181 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1182 mainWebView.getSettings().setLoadWithOverviewMode(true);
1184 // Explicitly disable geolocation.
1185 mainWebView.getSettings().setGeolocationEnabled(false);
1187 // Initialize cookieManager.
1188 cookieManager = CookieManager.getInstance();
1190 // Replace the header that `WebView` creates for `X-Requested-With` with a null value. The default value is the application ID (com.stoutner.privacybrowser.standard).
1191 customHeaders.put("X-Requested-With", "");
1193 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1194 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1196 // Get the intent that started the app.
1197 final Intent launchingIntent = getIntent();
1199 // Extract the launching intent data as `launchingIntentUriData`.
1200 final Uri launchingIntentUriData = launchingIntent.getData();
1202 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1203 if (launchingIntentUriData != null) {
1204 formattedUrlString = launchingIntentUriData.toString();
1207 // Get a handle for the `Runtime`.
1208 privacyBrowserRuntime = Runtime.getRuntime();
1210 // Store the application's private data directory.
1211 privateDataDirectoryString = getApplicationInfo().dataDir;
1212 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1214 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1215 inFullScreenBrowsingMode = false;
1217 // Initialize the privacy settings variables.
1218 javaScriptEnabled = false;
1219 firstPartyCookiesEnabled = false;
1220 thirdPartyCookiesEnabled = false;
1221 domStorageEnabled = false;
1222 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1225 // Store the default user agent.
1226 webViewDefaultUserAgent = mainWebView.getSettings().getUserAgentString();
1228 // Initialize the WebView title.
1229 webViewTitle = getString(R.string.no_title);
1231 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1232 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1233 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1234 assert favoriteIconBitmapDrawable != null;
1235 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1237 // If the favorite icon is null, load the default.
1238 if (favoriteIconBitmap == null) {
1239 favoriteIconBitmap = favoriteIconDefaultBitmap;
1242 // Initialize the user agent array adapter and string array.
1243 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1244 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1246 // Apply the app settings from the shared preferences.
1249 // Instantiate the block list helper.
1250 BlockListHelper blockListHelper = new BlockListHelper();
1252 // Initialize the list of resource requests.
1253 resourceRequests = new ArrayList<>();
1255 // Parse the block lists.
1256 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1257 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1258 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1259 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1260 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1262 // Store the list versions.
1263 easyListVersion = easyList.get(0).get(0)[0];
1264 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1265 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1266 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1267 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1269 // Get a handle for the activity. This is used to update the requests counter while the navigation menu is open.
1270 Activity activity = this;
1272 mainWebView.setWebViewClient(new WebViewClient() {
1273 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1274 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1275 @SuppressWarnings("deprecation")
1277 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1278 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1279 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1280 formattedUrlString = "";
1282 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1283 applyDomainSettings(url, true, false);
1285 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1287 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1288 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1289 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1291 // Parse the url and set it as the data for the intent.
1292 emailIntent.setData(Uri.parse(url));
1294 // Open the email program in a new task instead of as part of Privacy Browser.
1295 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1298 startActivity(emailIntent);
1300 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1302 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1303 // Open the dialer and load the phone number, but wait for the user to place the call.
1304 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1306 // Add the phone number to the intent.
1307 dialIntent.setData(Uri.parse(url));
1309 // Open the dialer in a new task instead of as part of Privacy Browser.
1310 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1313 startActivity(dialIntent);
1315 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1317 } else { // Load a system chooser to select an app that can handle the URL.
1318 // Open an app that can handle the URL.
1319 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1321 // Add the URL to the intent.
1322 genericIntent.setData(Uri.parse(url));
1324 // List all apps that can handle the URL instead of just opening the first one.
1325 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1327 // Open the app in a new task instead of as part of Privacy Browser.
1328 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1330 // Start the app or display a snackbar if no app is available to handle the URL.
1332 startActivity(genericIntent);
1333 } catch (ActivityNotFoundException exception) {
1334 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1337 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1342 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1343 @SuppressWarnings("deprecation")
1345 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1346 // Create an empty web resource response to be used if the resource request is blocked.
1347 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1349 // Reset the whitelist results tracker.
1350 whiteListResultStringArray = null;
1352 // Initialize the third party request tracker.
1353 boolean isThirdPartyRequest = false;
1355 // Initialize the current domain string.
1356 String currentDomain = "";
1358 // Nobody is happy when comparing null strings.
1359 if (!(formattedUrlString == null) && !(url == null)) {
1360 // Get the domain strings to URIs.
1361 Uri currentDomainUri = Uri.parse(formattedUrlString);
1362 Uri requestDomainUri = Uri.parse(url);
1364 // Get the domain host names.
1365 String currentBaseDomain = currentDomainUri.getHost();
1366 String requestBaseDomain = requestDomainUri.getHost();
1368 // Update the current domain variable.
1369 currentDomain = currentBaseDomain;
1371 // Only compare the current base domain and the request base domain if neither is null.
1372 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1373 // Determine the current base domain.
1374 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1375 // Remove the first subdomain.
1376 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1379 // Determine the request base domain.
1380 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1381 // Remove the first subdomain.
1382 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1385 // Update the third party request tracker.
1386 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1390 // Block third-party requests if enabled.
1391 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1392 // Increment the blocked requests counters.
1394 thirdPartyBlockedRequests++;
1396 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1397 activity.runOnUiThread(() -> {
1398 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1399 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1400 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1403 // Add the request to the log.
1404 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1406 // Return an empty web resource response.
1407 return emptyWebResourceResponse;
1410 // Check UltraPrivacy if it is enabled.
1411 if (ultraPrivacyEnabled) {
1412 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1413 // Increment the blocked requests counters.
1415 ultraPrivacyBlockedRequests++;
1417 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1418 activity.runOnUiThread(() -> {
1419 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1420 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1421 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1424 // The resource request was blocked. Return an empty web resource response.
1425 return emptyWebResourceResponse;
1428 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1429 if (whiteListResultStringArray != null) {
1430 // Add a whitelist entry to the resource requests array.
1431 resourceRequests.add(whiteListResultStringArray);
1433 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1438 // Check EasyList if it is enabled.
1439 if (easyListEnabled) {
1440 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1441 // Increment the blocked requests counters.
1443 easyListBlockedRequests++;
1445 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1446 activity.runOnUiThread(() -> {
1447 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1448 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1449 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1452 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1453 whiteListResultStringArray = null;
1455 // The resource request was blocked. Return an empty web resource response.
1456 return emptyWebResourceResponse;
1460 // Check EasyPrivacy if it is enabled.
1461 if (easyPrivacyEnabled) {
1462 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1463 // Increment the blocked requests counters.
1465 easyPrivacyBlockedRequests++;
1467 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1468 activity.runOnUiThread(() -> {
1469 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1470 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1471 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1474 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1475 whiteListResultStringArray = null;
1477 // The resource request was blocked. Return an empty web resource response.
1478 return emptyWebResourceResponse;
1482 // Check Fanboy’s Annoyance List if it is enabled.
1483 if (fanboysAnnoyanceListEnabled) {
1484 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1485 // Increment the blocked requests counters.
1487 fanboysAnnoyanceListBlockedRequests++;
1489 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1490 activity.runOnUiThread(() -> {
1491 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1492 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1493 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1496 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1497 whiteListResultStringArray = null;
1499 // The resource request was blocked. Return an empty web resource response.
1500 return emptyWebResourceResponse;
1502 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1503 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1504 // Increment the blocked requests counters.
1506 fanboysSocialBlockingListBlockedRequests++;
1508 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1509 activity.runOnUiThread(() -> {
1510 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1511 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1512 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1515 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1516 whiteListResultStringArray = null;
1518 // The resource request was blocked. Return an empty web resource response.
1519 return emptyWebResourceResponse;
1523 // Add the request to the log because it hasn't been processed by any of the previous checks.
1524 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1525 resourceRequests.add(whiteListResultStringArray);
1526 } else { // The request didn't match any blocklist entry. Log it as a defult request.
1527 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1530 // The resource request has not been blocked. `return null` loads the requested resource.
1534 // Handle HTTP authentication requests.
1536 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1537 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1538 httpAuthHandler = handler;
1540 // Display the HTTP authentication dialog.
1541 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1542 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1545 // Update the URL in urlTextBox when the page starts to load.
1547 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1548 // Reset the list of resource requests.
1549 resourceRequests.clear();
1551 // Initialize the counters for requests blocked by each blocklist.
1552 blockedRequests = 0;
1553 easyListBlockedRequests = 0;
1554 easyPrivacyBlockedRequests = 0;
1555 fanboysAnnoyanceListBlockedRequests = 0;
1556 fanboysSocialBlockingListBlockedRequests = 0;
1557 ultraPrivacyBlockedRequests = 0;
1558 thirdPartyBlockedRequests = 0;
1560 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1562 mainWebView.setVisibility(View.INVISIBLE);
1565 // Hide the keyboard. `0` indicates no additional flags.
1566 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1568 // Check to see if Privacy Browser is waiting on Orbot.
1569 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1570 // We need to update `formattedUrlString` at the beginning of the load, so that if the user toggles JavaScript during the load the new website is reloaded.
1571 formattedUrlString = url;
1573 // Display the formatted URL text.
1574 urlTextBox.setText(formattedUrlString);
1576 // Apply text highlighting to `urlTextBox`.
1579 // Apply any custom domain settings if the URL was loaded by navigating history.
1580 if (navigatingHistory) {
1581 // Reset `navigatingHistory`.
1582 navigatingHistory = false;
1584 // Apply the domain settings.
1585 applyDomainSettings(url, true, false);
1588 // Set `urlIsLoading` to `true`, so that redirects while loading do not trigger changes in the user agent, which forces another reload of the existing page.
1589 urlIsLoading = true;
1591 // Replace Refresh with Stop if the menu item has been created. (The WebView typically begins loading before the menu items are instantiated.)
1592 if (refreshMenuItem != null) {
1594 refreshMenuItem.setTitle(R.string.stop);
1596 // If the icon is displayed in the AppBar, set it according to the theme.
1597 if (displayAdditionalAppBarIcons) {
1599 refreshMenuItem.setIcon(R.drawable.close_dark);
1601 refreshMenuItem.setIcon(R.drawable.close_light);
1608 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1610 public void onPageFinished(WebView view, String url) {
1611 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1612 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1613 cookieManager.flush();
1616 // Update the Refresh menu item if it has been created.
1617 if (refreshMenuItem != null) {
1618 // Reset the Refresh title.
1619 refreshMenuItem.setTitle(R.string.refresh);
1621 // If the icon is displayed in the AppBar, reset it according to the theme.
1622 if (displayAdditionalAppBarIcons) {
1624 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1626 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1631 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1632 urlIsLoading = false;
1634 // Clear the cache and history if Incognito Mode is enabled.
1635 if (incognitoModeEnabled) {
1636 // Clear the cache. `true` includes disk files.
1637 mainWebView.clearCache(true);
1639 // Clear the back/forward history.
1640 mainWebView.clearHistory();
1642 // Manually delete cache folders.
1644 // Delete the main cache directory.
1645 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1647 // Delete the secondary `Service Worker` cache directory.
1648 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1649 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1650 } catch (IOException e) {
1651 // Do nothing if an error is thrown.
1655 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1656 if (!waitingForOrbot) {
1657 // Check to see if `WebView` has set `url` to be `about:blank`.
1658 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1659 // Set `formattedUrlString` to `""`.
1660 formattedUrlString = "";
1662 urlTextBox.setText(formattedUrlString);
1664 // Request focus for `urlTextBox`.
1665 urlTextBox.requestFocus();
1667 // Display the keyboard.
1668 inputMethodManager.showSoftInput(urlTextBox, 0);
1670 // Apply the domain settings. This clears any settings from the previous domain.
1671 applyDomainSettings(formattedUrlString, true, false);
1672 } else { // `WebView` has loaded a webpage.
1673 // Set `formattedUrlString`.
1674 formattedUrlString = url;
1676 // Only update `urlTextBox` if the user is not typing in it.
1677 if (!urlTextBox.hasFocus()) {
1678 // Display the formatted URL text.
1679 urlTextBox.setText(formattedUrlString);
1681 // Apply text highlighting to `urlTextBox`.
1686 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1687 sslCertificate = mainWebView.getCertificate();
1689 // Check the current website SSL certificate against the pinned SSL certificate if there is a pinned SSL certificate the user has not chosen to ignore it for this session.
1690 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1691 // Initialize the current SSL certificate variables.
1692 String currentWebsiteIssuedToCName = "";
1693 String currentWebsiteIssuedToOName = "";
1694 String currentWebsiteIssuedToUName = "";
1695 String currentWebsiteIssuedByCName = "";
1696 String currentWebsiteIssuedByOName = "";
1697 String currentWebsiteIssuedByUName = "";
1698 Date currentWebsiteSslStartDate = null;
1699 Date currentWebsiteSslEndDate = null;
1702 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1703 if (sslCertificate != null) {
1704 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1705 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1706 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1707 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1708 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1709 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1710 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1711 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1714 // Initialize `String` variables to store the SSL certificate dates. `Strings` are needed to compare the values below, which doesn't work with `Dates` if they are `null`.
1715 String currentWebsiteSslStartDateString = "";
1716 String currentWebsiteSslEndDateString = "";
1717 String pinnedDomainSslStartDateString = "";
1718 String pinnedDomainSslEndDateString = "";
1720 // Convert the `Dates` to `Strings` if they are not `null`.
1721 if (currentWebsiteSslStartDate != null) {
1722 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1725 if (currentWebsiteSslEndDate != null) {
1726 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1729 if (pinnedDomainSslStartDate != null) {
1730 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1733 if (pinnedDomainSslEndDate != null) {
1734 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1737 // Check to see if the pinned SSL certificate matches the current website certificate.
1738 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1739 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1740 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1741 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1742 // The pinned SSL certificate doesn't match the current domain certificate.
1743 //Display the pinned SSL certificate mismatch `AlertDialog`.
1744 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1745 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1751 // Handle SSL Certificate errors.
1753 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1754 // Get the current website SSL certificate.
1755 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1757 // Extract the individual pieces of information from the current website SSL certificate.
1758 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1759 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1760 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1761 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1762 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1763 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1764 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1765 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1767 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1768 if (pinnedDomainSslCertificate &&
1769 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1770 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1771 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1772 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1773 // An SSL certificate is pinned and matches the current domain certificate.
1774 // Proceed to the website without displaying an error.
1776 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1777 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1778 sslErrorHandler = handler;
1780 // Display the SSL error `AlertDialog`.
1781 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1782 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1787 // Load the website if not waiting for Orbot to connect.
1788 if (!waitingForOrbot) {
1789 loadUrl(formattedUrlString);
1794 protected void onNewIntent(Intent intent) {
1795 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1798 // Check to see if the intent contains a new URL.
1799 if (intent.getData() != null) {
1800 // Get the intent data.
1801 final Uri intentUriData = intent.getData();
1803 // Load the website.
1804 loadUrl(intentUriData.toString());
1806 // Close the navigation drawer if it is open.
1807 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1808 drawerLayout.closeDrawer(GravityCompat.START);
1811 // Close the bookmarks drawer if it is open.
1812 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1813 drawerLayout.closeDrawer(GravityCompat.END);
1816 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1817 mainWebView.requestFocus();
1822 public void onRestart() {
1823 // Run the default commands.
1826 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1827 if (proxyThroughOrbot) {
1828 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1829 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1831 // Send the intent to the Orbot package.
1832 orbotIntent.setPackage("org.torproject.android");
1835 sendBroadcast(orbotIntent);
1838 // Apply the app settings if returning from the Settings activity..
1839 if (reapplyAppSettingsOnRestart) {
1840 // Apply the app settings.
1843 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1844 if (reloadOnRestart) {
1845 // Reload `mainWebView`.
1846 mainWebView.reload();
1848 // Reset `reloadOnRestartBoolean`.
1849 reloadOnRestart = false;
1852 // Reset the return from settings flag.
1853 reapplyAppSettingsOnRestart = false;
1856 // Apply the domain settings if returning from the Domains activity.
1857 if (reapplyDomainSettingsOnRestart) {
1858 // Reapply the domain settings.
1859 applyDomainSettings(formattedUrlString, false, true);
1861 // Reset `reapplyDomainSettingsOnRestart`.
1862 reapplyDomainSettingsOnRestart = false;
1865 // Load the URL on restart to apply changes to night mode.
1866 if (loadUrlOnRestart) {
1867 // Load the current `formattedUrlString`.
1868 loadUrl(formattedUrlString);
1870 // Reset `loadUrlOnRestart.
1871 loadUrlOnRestart = false;
1874 // Update the bookmarks drawer if returning from the Bookmarks activity.
1875 if (restartFromBookmarksActivity) {
1876 // Close the bookmarks drawer.
1877 drawerLayout.closeDrawer(GravityCompat.END);
1879 // Reload the bookmarks drawer.
1880 loadBookmarksFolder();
1882 // Reset `restartFromBookmarksActivity`.
1883 restartFromBookmarksActivity = false;
1886 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1887 updatePrivacyIcons(true);
1890 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1892 public void onResume() {
1893 // Run the default commands.
1896 // Resume JavaScript (if enabled).
1897 mainWebView.resumeTimers();
1899 // Resume `mainWebView`.
1900 mainWebView.onResume();
1902 // Resume the adView for the free flavor.
1903 if (BuildConfig.FLAVOR.contentEquals("free")) {
1905 AdHelper.resumeAd(findViewById(R.id.adview));
1908 // Display a message to the user if waiting for Orbot.
1909 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1910 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1911 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1914 if (displayingFullScreenVideo) {
1915 // Remove the translucent overlays.
1916 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1918 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1919 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1921 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1922 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1923 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1925 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1930 public void onPause() {
1931 // Run the default commands.
1934 // Pause `mainWebView`.
1935 mainWebView.onPause();
1937 // Stop all JavaScript.
1938 mainWebView.pauseTimers();
1940 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1941 if (BuildConfig.FLAVOR.contentEquals("free")) {
1943 AdHelper.pauseAd(findViewById(R.id.adview));
1948 public void onDestroy() {
1949 // Unregister the Orbot status broadcast receiver.
1950 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1952 // Run the default commands.
1957 public boolean onCreateOptionsMenu(Menu menu) {
1958 // Inflate the menu; this adds items to the action bar if it is present.
1959 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1961 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1964 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1965 updatePrivacyIcons(false);
1967 // Get handles for the menu items.
1968 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1969 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1970 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1971 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1972 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1973 refreshMenuItem = menu.findItem(R.id.refresh);
1974 blocklistsMenuItem = menu.findItem(R.id.blocklists);
1975 easyListMenuItem = menu.findItem(R.id.easylist);
1976 easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1977 fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1978 fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1979 ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1980 blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1981 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1983 // Only display third-party cookies if API >= 21
1984 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1986 // Only display the form data menu items if the API < 26.
1987 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1988 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1990 // Only show Ad Consent if this is the free flavor.
1991 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1993 // Get the shared preference values.
1994 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1996 // Get the status of the additional AppBar icons.
1997 displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1999 // Set the status of the additional app bar icons. Setting the refresh menu item to `SHOW_AS_ACTION_ALWAYS` makes it appear even on small devices like phones.
2000 if (displayAdditionalAppBarIcons) {
2001 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2002 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2003 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
2004 } else { //Do not display the additional icons.
2005 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2006 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2007 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2010 // Replace Refresh with Stop if a URL is already loading.
2013 refreshMenuItem.setTitle(R.string.stop);
2015 // If the icon is displayed in the AppBar, set it according to the theme.
2016 if (displayAdditionalAppBarIcons) {
2018 refreshMenuItem.setIcon(R.drawable.close_dark);
2020 refreshMenuItem.setIcon(R.drawable.close_light);
2029 public boolean onPrepareOptionsMenu(Menu menu) {
2030 // Get handles for the menu items.
2031 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2032 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2033 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2034 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2035 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
2036 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2037 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2038 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2039 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
2040 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2041 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
2042 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2044 // Set the text for the domain menu item.
2045 if (domainSettingsApplied) {
2046 addOrEditDomain.setTitle(R.string.edit_domain_settings);
2048 addOrEditDomain.setTitle(R.string.add_domain_settings);
2051 // Set the status of the menu item checkboxes.
2052 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2053 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2054 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2055 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
2056 easyListMenuItem.setChecked(easyListEnabled);
2057 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
2058 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
2059 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
2060 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
2061 blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
2062 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
2063 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2065 // Enable third-party cookies if first-party cookies are enabled.
2066 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2068 // Enable DOM Storage if JavaScript is enabled.
2069 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2071 // Enable Clear Cookies if there are any.
2072 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2074 // Get a count of the number of files in the Local Storage directory.
2075 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2076 int localStorageDirectoryNumberOfFiles = 0;
2077 if (localStorageDirectory.exists()) {
2078 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2081 // Get a count of the number of files in the IndexedDB directory.
2082 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2083 int indexedDBDirectoryNumberOfFiles = 0;
2084 if (indexedDBDirectory.exists()) {
2085 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2088 // Enable Clear DOM Storage if there is any.
2089 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2091 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
2092 if (Build.VERSION.SDK_INT < 26) {
2093 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2094 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2096 // Disable clear form data because it is not supported on current version of Android.
2097 clearFormDataMenuItem.setEnabled(false);
2100 // Enable Clear Data if any of the submenu items are enabled.
2101 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2103 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2104 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2106 // Initialize the display names for the blocklists with the number of blocked requests.
2107 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
2108 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2109 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2110 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2111 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2112 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2113 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2115 // Get the current user agent.
2116 String currentUserAgent = mainWebView.getSettings().getUserAgentString();
2118 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
2119 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
2120 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
2121 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
2122 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
2123 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
2124 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
2125 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
2126 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
2127 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
2128 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
2129 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
2130 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
2131 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
2132 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
2133 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
2134 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
2135 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
2136 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
2137 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
2138 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
2139 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
2140 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
2141 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
2142 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
2143 } else { // Custom user agent.
2144 menu.findItem(R.id.user_agent_custom).setChecked(true);
2147 // Initialize font size variables.
2148 int fontSize = mainWebView.getSettings().getTextZoom();
2149 String fontSizeTitle;
2150 MenuItem selectedFontSizeMenuItem;
2152 // Prepare the font size title and current size menu item.
2155 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2156 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2160 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2161 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2165 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2166 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2170 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2171 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2175 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2176 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2180 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2181 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2185 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2186 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2190 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2191 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2195 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2196 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2200 // Set the font size title and select the current size menu item.
2201 fontSizeMenuItem.setTitle(fontSizeTitle);
2202 selectedFontSizeMenuItem.setChecked(true);
2204 // Run all the other default commands.
2205 super.onPrepareOptionsMenu(menu);
2207 // Display the menu.
2212 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2213 @SuppressLint("SetJavaScriptEnabled")
2214 // removeAllCookies is deprecated, but it is required for API < 21.
2215 @SuppressWarnings("deprecation")
2216 public boolean onOptionsItemSelected(MenuItem menuItem) {
2217 // Get the selected menu item ID.
2218 int menuItemId = menuItem.getItemId();
2220 // Set the commands that relate to the menu entries.
2221 switch (menuItemId) {
2222 case R.id.toggle_javascript:
2223 // Switch the status of javaScriptEnabled.
2224 javaScriptEnabled = !javaScriptEnabled;
2226 // Apply the new JavaScript status.
2227 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2229 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2230 updatePrivacyIcons(true);
2232 // Display a `Snackbar`.
2233 if (javaScriptEnabled) { // JavaScrip is enabled.
2234 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2235 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2236 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2237 } else { // Privacy mode.
2238 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2241 // Reload the WebView.
2242 mainWebView.reload();
2245 case R.id.add_or_edit_domain:
2246 if (domainSettingsApplied) { // Edit the current domain settings.
2247 // Reapply the domain settings on returning to `MainWebViewActivity`.
2248 reapplyDomainSettingsOnRestart = true;
2249 currentDomainName = "";
2251 // Create an intent to launch the domains activity.
2252 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2254 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2255 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2256 domainsIntent.putExtra("closeOnBack", true);
2259 startActivity(domainsIntent);
2260 } else { // Add a new domain.
2261 // Apply the new domain settings on returning to `MainWebViewActivity`.
2262 reapplyDomainSettingsOnRestart = true;
2263 currentDomainName = "";
2265 // Get the current domain
2266 Uri currentUri = Uri.parse(formattedUrlString);
2267 String currentDomain = currentUri.getHost();
2269 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2270 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2272 // Create the domain and store the database ID.
2273 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2275 // Create an intent to launch the domains activity.
2276 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2278 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2279 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2280 domainsIntent.putExtra("closeOnBack", true);
2283 startActivity(domainsIntent);
2287 case R.id.toggle_first_party_cookies:
2288 // Switch the status of firstPartyCookiesEnabled.
2289 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2291 // Update the menu checkbox.
2292 menuItem.setChecked(firstPartyCookiesEnabled);
2294 // Apply the new cookie status.
2295 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2297 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2298 updatePrivacyIcons(true);
2300 // Display a `Snackbar`.
2301 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2302 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2303 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2304 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2305 } else { // Privacy mode.
2306 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2309 // Reload the WebView.
2310 mainWebView.reload();
2313 case R.id.toggle_third_party_cookies:
2314 if (Build.VERSION.SDK_INT >= 21) {
2315 // Switch the status of thirdPartyCookiesEnabled.
2316 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2318 // Update the menu checkbox.
2319 menuItem.setChecked(thirdPartyCookiesEnabled);
2321 // Apply the new cookie status.
2322 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2324 // Display a `Snackbar`.
2325 if (thirdPartyCookiesEnabled) {
2326 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2328 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2331 // Reload the WebView.
2332 mainWebView.reload();
2333 } // Else do nothing because SDK < 21.
2336 case R.id.toggle_dom_storage:
2337 // Switch the status of domStorageEnabled.
2338 domStorageEnabled = !domStorageEnabled;
2340 // Update the menu checkbox.
2341 menuItem.setChecked(domStorageEnabled);
2343 // Apply the new DOM Storage status.
2344 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2346 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2347 updatePrivacyIcons(true);
2349 // Display a `Snackbar`.
2350 if (domStorageEnabled) {
2351 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2353 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2356 // Reload the WebView.
2357 mainWebView.reload();
2360 // Form data can be removed once the minimum API >= 26.
2361 case R.id.toggle_save_form_data:
2362 // Switch the status of saveFormDataEnabled.
2363 saveFormDataEnabled = !saveFormDataEnabled;
2365 // Update the menu checkbox.
2366 menuItem.setChecked(saveFormDataEnabled);
2368 // Apply the new form data status.
2369 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2371 // Display a `Snackbar`.
2372 if (saveFormDataEnabled) {
2373 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2375 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2378 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2379 updatePrivacyIcons(true);
2381 // Reload the WebView.
2382 mainWebView.reload();
2385 case R.id.clear_cookies:
2386 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2387 .setAction(R.string.undo, v -> {
2388 // Do nothing because everything will be handled by `onDismissed()` below.
2390 .addCallback(new Snackbar.Callback() {
2392 public void onDismissed(Snackbar snackbar, int event) {
2394 // The user pushed the `Undo` button.
2395 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2399 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2401 // `cookieManager.removeAllCookie()` varies by SDK.
2402 if (Build.VERSION.SDK_INT < 21) {
2403 cookieManager.removeAllCookie();
2405 // `null` indicates no callback.
2406 cookieManager.removeAllCookies(null);
2414 case R.id.clear_dom_storage:
2415 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2416 .setAction(R.string.undo, v -> {
2417 // Do nothing because everything will be handled by `onDismissed()` below.
2419 .addCallback(new Snackbar.Callback() {
2421 public void onDismissed(Snackbar snackbar, int event) {
2423 // The user pushed the `Undo` button.
2424 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2428 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2430 // Delete the DOM Storage.
2431 WebStorage webStorage = WebStorage.getInstance();
2432 webStorage.deleteAllData();
2434 // Manually delete the DOM storage files and directories.
2436 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2437 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2439 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2440 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2441 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2442 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2443 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2444 } catch (IOException e) {
2445 // Do nothing if an error is thrown.
2453 // Form data can be remove once the minimum API >= 26.
2454 case R.id.clear_form_data:
2455 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2456 .setAction(R.string.undo, v -> {
2457 // Do nothing because everything will be handled by `onDismissed()` below.
2459 .addCallback(new Snackbar.Callback() {
2461 public void onDismissed(Snackbar snackbar, int event) {
2463 // The user pushed the `Undo` button.
2464 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2468 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2470 // Delete the form data.
2471 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2472 mainWebViewDatabase.clearFormData();
2480 // Toggle the EasyList status.
2481 easyListEnabled = !easyListEnabled;
2483 // Update the menu checkbox.
2484 menuItem.setChecked(easyListEnabled);
2486 // Reload the main WebView.
2487 mainWebView.reload();
2490 case R.id.easyprivacy:
2491 // Toggle the EasyPrivacy status.
2492 easyPrivacyEnabled = !easyPrivacyEnabled;
2494 // Update the menu checkbox.
2495 menuItem.setChecked(easyPrivacyEnabled);
2497 // Reload the main WebView.
2498 mainWebView.reload();
2501 case R.id.fanboys_annoyance_list:
2502 // Toggle Fanboy's Annoyance List status.
2503 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2505 // Update the menu checkbox.
2506 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2508 // Update the staus of Fanboy's Social Blocking List.
2509 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2510 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2512 // Reload the main WebView.
2513 mainWebView.reload();
2516 case R.id.fanboys_social_blocking_list:
2517 // Toggle Fanboy's Social Blocking List status.
2518 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2520 // Update the menu checkbox.
2521 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2523 // Reload the main WebView.
2524 mainWebView.reload();
2527 case R.id.ultraprivacy:
2528 // Toggle the UltraPrivacy status.
2529 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2531 // Update the menu checkbox.
2532 menuItem.setChecked(ultraPrivacyEnabled);
2534 // Reload the main WebView.
2535 mainWebView.reload();
2538 case R.id.block_all_third_party_requests:
2539 //Toggle the third-party requests blocker status.
2540 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2542 // Update the menu checkbox.
2543 menuItem.setChecked(blockAllThirdPartyRequests);
2545 // Reload the main WebView.
2546 mainWebView.reload();
2549 case R.id.user_agent_privacy_browser:
2550 // Update the user agent.
2551 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
2553 // Reload the WebView.
2554 mainWebView.reload();
2557 case R.id.user_agent_webview_default:
2558 // Update the user agent.
2559 mainWebView.getSettings().setUserAgentString("");
2561 // Reload the WebView.
2562 mainWebView.reload();
2565 case R.id.user_agent_firefox_on_android:
2566 // Update the user agent.
2567 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
2569 // Reload the WebView.
2570 mainWebView.reload();
2573 case R.id.user_agent_chrome_on_android:
2574 // Update the user agent.
2575 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
2577 // Reload the WebView.
2578 mainWebView.reload();
2581 case R.id.user_agent_safari_on_ios:
2582 // Update the user agent.
2583 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
2585 // Reload the WebView.
2586 mainWebView.reload();
2589 case R.id.user_agent_firefox_on_linux:
2590 // Update the user agent.
2591 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
2593 // Reload the WebView.
2594 mainWebView.reload();
2597 case R.id.user_agent_chromium_on_linux:
2598 // Update the user agent.
2599 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
2601 // Reload the WebView.
2602 mainWebView.reload();
2605 case R.id.user_agent_firefox_on_windows:
2606 // Update the user agent.
2607 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
2609 // Reload the WebView.
2610 mainWebView.reload();
2613 case R.id.user_agent_chrome_on_windows:
2614 // Update the user agent.
2615 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
2617 // Reload the WebView.
2618 mainWebView.reload();
2621 case R.id.user_agent_edge_on_windows:
2622 // Update the user agent.
2623 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
2625 // Reload the WebView.
2626 mainWebView.reload();
2629 case R.id.user_agent_internet_explorer_on_windows:
2630 // Update the user agent.
2631 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
2633 // Reload the WebView.
2634 mainWebView.reload();
2637 case R.id.user_agent_safari_on_macos:
2638 // Update the user agent.
2639 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
2641 // Reload the WebView.
2642 mainWebView.reload();
2645 case R.id.user_agent_custom:
2646 // Update the user agent.
2647 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2649 // Reload the WebView.
2650 mainWebView.reload();
2653 case R.id.font_size_twenty_five_percent:
2654 mainWebView.getSettings().setTextZoom(25);
2657 case R.id.font_size_fifty_percent:
2658 mainWebView.getSettings().setTextZoom(50);
2661 case R.id.font_size_seventy_five_percent:
2662 mainWebView.getSettings().setTextZoom(75);
2665 case R.id.font_size_one_hundred_percent:
2666 mainWebView.getSettings().setTextZoom(100);
2669 case R.id.font_size_one_hundred_twenty_five_percent:
2670 mainWebView.getSettings().setTextZoom(125);
2673 case R.id.font_size_one_hundred_fifty_percent:
2674 mainWebView.getSettings().setTextZoom(150);
2677 case R.id.font_size_one_hundred_seventy_five_percent:
2678 mainWebView.getSettings().setTextZoom(175);
2681 case R.id.font_size_two_hundred_percent:
2682 mainWebView.getSettings().setTextZoom(200);
2685 case R.id.swipe_to_refresh:
2686 // Toggle swipe to refresh.
2687 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2690 case R.id.display_images:
2691 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2692 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2693 mainWebView.reload();
2694 } else { // Images are not currently loaded automatically.
2695 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2698 // Set `onTheFlyDisplayImagesSet`.
2699 onTheFlyDisplayImagesSet = true;
2702 case R.id.view_source:
2703 // Launch the View Source activity.
2704 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2705 startActivity(viewSourceIntent);
2709 // Setup the share string.
2710 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2712 // Create the share intent.
2713 Intent shareIntent = new Intent();
2714 shareIntent.setAction(Intent.ACTION_SEND);
2715 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2716 shareIntent.setType("text/plain");
2719 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2722 case R.id.find_on_page:
2723 // Hide the URL app bar.
2724 supportAppBar.setVisibility(View.GONE);
2726 // Show the Find on Page `RelativeLayout`.
2727 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2729 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2730 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2731 findOnPageEditText.postDelayed(() -> {
2732 // Set the focus on `findOnPageEditText`.
2733 findOnPageEditText.requestFocus();
2735 // Display the keyboard. `0` sets no input flags.
2736 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2741 // Get a `PrintManager` instance.
2742 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2744 // Convert `mainWebView` to `printDocumentAdapter`.
2745 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2747 // Remove the lint error below that `printManager` might be `null`.
2748 assert printManager != null;
2750 // Print the document. The print attributes are `null`.
2751 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2754 case R.id.add_to_homescreen:
2755 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2756 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2757 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2759 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2763 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2764 // Reload the WebView.
2765 mainWebView.reload();
2766 } else { // The stop button was pushed.
2767 // Stop the loading of the WebView.
2768 mainWebView.stopLoading();
2772 case R.id.ad_consent:
2773 // Display the ad consent dialog.
2774 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2775 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2779 // Don't consume the event.
2780 return super.onOptionsItemSelected(menuItem);
2784 // removeAllCookies is deprecated, but it is required for API < 21.
2785 @SuppressWarnings("deprecation")
2787 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2788 int menuItemId = menuItem.getItemId();
2790 switch (menuItemId) {
2796 if (mainWebView.canGoBack()) {
2797 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2798 formattedUrlString = "";
2800 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2801 navigatingHistory = true;
2803 // Load the previous website in the history.
2804 mainWebView.goBack();
2809 if (mainWebView.canGoForward()) {
2810 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2811 formattedUrlString = "";
2813 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2814 navigatingHistory = true;
2816 // Load the next website in the history.
2817 mainWebView.goForward();
2822 // Get the `WebBackForwardList`.
2823 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2825 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2826 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2827 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2831 // Launch the requests activity.
2832 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2833 startActivity(requestsIntent);
2836 case R.id.downloads:
2837 // Launch the system Download Manager.
2838 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2840 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2841 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2843 startActivity(downloadManagerIntent);
2847 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2848 reapplyDomainSettingsOnRestart = true;
2849 currentDomainName = "";
2851 // Launch the domains activity.
2852 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2853 startActivity(domainsIntent);
2857 // Set the flag to reapply app settings on restart when returning from Settings.
2858 reapplyAppSettingsOnRestart = true;
2860 // Set the flag to reapply the domain settings on restart when returning from Settings.
2861 reapplyDomainSettingsOnRestart = true;
2862 currentDomainName = "";
2864 // Launch the settings activity.
2865 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2866 startActivity(settingsIntent);
2870 // Launch `GuideActivity`.
2871 Intent guideIntent = new Intent(this, GuideActivity.class);
2872 startActivity(guideIntent);
2876 // Launch `AboutActivity`.
2877 Intent aboutIntent = new Intent(this, AboutActivity.class);
2878 startActivity(aboutIntent);
2881 case R.id.clearAndExit:
2882 // Get a handle for `sharedPreferences`. `this` references the current context.
2883 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2885 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2888 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2889 // The command to remove cookies changed slightly in API 21.
2890 if (Build.VERSION.SDK_INT >= 21) {
2891 cookieManager.removeAllCookies(null);
2893 cookieManager.removeAllCookie();
2896 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2898 // We have to use two commands because `Runtime.exec()` does not like `*`.
2899 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2900 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2901 } catch (IOException e) {
2902 // Do nothing if an error is thrown.
2906 // Clear DOM storage.
2907 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2908 // Ask `WebStorage` to clear the DOM storage.
2909 WebStorage webStorage = WebStorage.getInstance();
2910 webStorage.deleteAllData();
2912 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2914 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2915 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2917 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2918 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2919 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2920 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2921 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2922 } catch (IOException e) {
2923 // Do nothing if an error is thrown.
2927 // Clear form data if the API < 26.
2928 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2929 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2930 webViewDatabase.clearFormData();
2932 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2934 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2935 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2936 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2937 } catch (IOException e) {
2938 // Do nothing if an error is thrown.
2943 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2944 // `true` includes disk files.
2945 mainWebView.clearCache(true);
2947 // Manually delete the cache directories.
2949 // Delete the main cache directory.
2950 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2952 // Delete the secondary `Service Worker` cache directory.
2953 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2954 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2955 } catch (IOException e) {
2956 // Do nothing if an error is thrown.
2960 // Clear SSL certificate preferences.
2961 mainWebView.clearSslPreferences();
2963 // Clear the back/forward history.
2964 mainWebView.clearHistory();
2966 // Clear `formattedUrlString`.
2967 formattedUrlString = null;
2969 // Clear `customHeaders`.
2970 customHeaders.clear();
2972 // Detach all views from `mainWebViewRelativeLayout`.
2973 mainWebViewRelativeLayout.removeAllViews();
2975 // Destroy the internal state of `mainWebView`.
2976 mainWebView.destroy();
2978 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2979 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2980 if (clearEverything) {
2982 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2983 } catch (IOException e) {
2984 // Do nothing if an error is thrown.
2988 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2989 if (Build.VERSION.SDK_INT >= 21) {
2990 finishAndRemoveTask();
2995 // Remove the terminated program from RAM. The status code is `0`.
3000 // Close the navigation drawer.
3001 drawerLayout.closeDrawer(GravityCompat.START);
3006 public void onPostCreate(Bundle savedInstanceState) {
3007 super.onPostCreate(savedInstanceState);
3009 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
3010 drawerToggle.syncState();
3014 public void onConfigurationChanged(Configuration newConfig) {
3015 super.onConfigurationChanged(newConfig);
3017 // Reload the ad for the free flavor if we not in full screen mode.
3018 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
3019 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3020 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
3023 // `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:
3024 // https://code.google.com/p/android/issues/detail?id=20493#c8
3025 // ActivityCompat.invalidateOptionsMenu(this);
3029 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
3030 // Store the `HitTestResult`.
3031 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
3034 final String imageUrl;
3035 final String linkUrl;
3037 // Get a handle for the `ClipboardManager`.
3038 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
3040 // Remove the lint errors below that `clipboardManager` might be `null`.
3041 assert clipboardManager != null;
3043 switch (hitTestResult.getType()) {
3044 // `SRC_ANCHOR_TYPE` is a link.
3045 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
3046 // Get the target URL.
3047 linkUrl = hitTestResult.getExtra();
3049 // Set the target URL as the title of the `ContextMenu`.
3050 menu.setHeaderTitle(linkUrl);
3052 // Add a Load URL entry.
3053 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
3058 // Add a Copy URL entry.
3059 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
3060 // Save the link URL in a `ClipData`.
3061 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
3063 // Set the `ClipData` as the clipboard's primary clip.
3064 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
3068 // Add a Download URL entry.
3069 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
3070 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3071 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3072 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3074 // Store the variables for future use by `onRequestPermissionsResult()`.
3075 downloadUrl = linkUrl;
3076 downloadContentDisposition = "none";
3077 downloadContentLength = -1;
3079 // Show a dialog if the user has previously denied the permission.
3080 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3081 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
3082 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
3084 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
3085 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3086 } else { // Show the permission request directly.
3087 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
3088 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3090 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3091 // Get a handle for the download file alert dialog.
3092 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
3094 // Show the download file alert dialog.
3095 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3100 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3101 menu.add(R.string.cancel);
3104 case WebView.HitTestResult.EMAIL_TYPE:
3105 // Get the target URL.
3106 linkUrl = hitTestResult.getExtra();
3108 // Set the target URL as the title of the `ContextMenu`.
3109 menu.setHeaderTitle(linkUrl);
3111 // Add a `Write Email` entry.
3112 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
3113 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
3114 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
3116 // Parse the url and set it as the data for the `Intent`.
3117 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
3119 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
3120 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3123 startActivity(emailIntent);
3127 // Add a `Copy Email Address` entry.
3128 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
3129 // Save the email address in a `ClipData`.
3130 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
3132 // Set the `ClipData` as the clipboard's primary clip.
3133 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
3137 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3138 menu.add(R.string.cancel);
3141 // `IMAGE_TYPE` is an image.
3142 case WebView.HitTestResult.IMAGE_TYPE:
3143 // Get the image URL.
3144 imageUrl = hitTestResult.getExtra();
3146 // Set the image URL as the title of the `ContextMenu`.
3147 menu.setHeaderTitle(imageUrl);
3149 // Add a `View Image` entry.
3150 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3155 // Add a `Download Image` entry.
3156 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3157 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3158 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3159 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3161 // Store the image URL for use by `onRequestPermissionResult()`.
3162 downloadImageUrl = imageUrl;
3164 // Show a dialog if the user has previously denied the permission.
3165 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3166 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3167 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3169 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3170 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3171 } else { // Show the permission request directly.
3172 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3173 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3175 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3176 // Get a handle for the download image alert dialog.
3177 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3179 // Show the download image alert dialog.
3180 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3185 // Add a `Copy URL` entry.
3186 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3187 // Save the image URL in a `ClipData`.
3188 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3190 // Set the `ClipData` as the clipboard's primary clip.
3191 clipboardManager.setPrimaryClip(srcImageTypeClipData);
3195 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3196 menu.add(R.string.cancel);
3200 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
3201 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
3202 // Get the image URL.
3203 imageUrl = hitTestResult.getExtra();
3205 // Set the image URL as the title of the `ContextMenu`.
3206 menu.setHeaderTitle(imageUrl);
3208 // Add a `View Image` entry.
3209 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3214 // Add a `Download Image` entry.
3215 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3216 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3217 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3218 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3220 // Store the image URL for use by `onRequestPermissionResult()`.
3221 downloadImageUrl = imageUrl;
3223 // Show a dialog if the user has previously denied the permission.
3224 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3225 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3226 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3228 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3229 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3230 } else { // Show the permission request directly.
3231 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3232 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3234 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3235 // Get a handle for the download image alert dialog.
3236 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3238 // Show the download image alert dialog.
3239 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3244 // Add a `Copy URL` entry.
3245 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3246 // Save the image URL in a `ClipData`.
3247 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3249 // Set the `ClipData` as the clipboard's primary clip.
3250 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3254 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3255 menu.add(R.string.cancel);
3261 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3262 // Get the `EditTexts` from the `dialogFragment`.
3263 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3264 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3266 // Extract the strings from the `EditTexts`.
3267 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3268 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3270 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3271 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3272 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3273 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3275 // Display the new bookmark below the current items in the (0 indexed) list.
3276 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3278 // Create the bookmark.
3279 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3281 // Update `bookmarksCursor` with the current contents of this folder.
3282 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3284 // Update the `ListView`.
3285 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3287 // Scroll to the new bookmark.
3288 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3292 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3293 // Get handles for the views in `dialogFragment`.
3294 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3295 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3296 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3298 // Get new folder name string.
3299 String folderNameString = createFolderNameEditText.getText().toString();
3301 // Get the new folder icon `Bitmap`.
3302 Bitmap folderIconBitmap;
3303 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3304 // Get the default folder icon and convert it to a `Bitmap`.
3305 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3306 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3307 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3308 } else { // Use the `WebView` favorite icon.
3309 folderIconBitmap = favoriteIconBitmap;
3312 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3313 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3314 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3315 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3317 // Move all the bookmarks down one in the display order.
3318 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3319 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3320 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3323 // Create the folder, which will be placed at the top of the `ListView`.
3324 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3326 // Update `bookmarksCursor` with the current contents of this folder.
3327 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3329 // Update the `ListView`.
3330 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3332 // Scroll to the new folder.
3333 bookmarksListView.setSelection(0);
3337 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3338 // Get the shortcut name.
3339 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3340 String shortcutNameString = shortcutNameEditText.getText().toString();
3342 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3343 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3345 // Setup the shortcut intent.
3346 Intent shortcutIntent = new Intent();
3347 shortcutIntent.setAction(Intent.ACTION_VIEW);
3348 shortcutIntent.setData(Uri.parse(formattedUrlString));
3350 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3351 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3353 // Add the required fields to the shortcut info builder.
3354 shortcutInfoBuilder.setIcon(favoriteIcon);
3355 shortcutInfoBuilder.setIntent(shortcutIntent);
3356 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3358 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3359 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3363 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3364 switch (downloadType) {
3365 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3366 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3367 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3370 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3371 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3372 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3378 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
3379 switch (requestCode) {
3380 case DOWNLOAD_FILE_REQUEST_CODE:
3381 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3382 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3384 // On API 23, displaying the fragment must be delayed or the app will crash.
3385 if (Build.VERSION.SDK_INT == 23) {
3386 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3388 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3391 // Reset the download variables.
3393 downloadContentDisposition = "";
3394 downloadContentLength = 0;
3397 case DOWNLOAD_IMAGE_REQUEST_CODE:
3398 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3399 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3401 // On API 23, displaying the fragment must be delayed or the app will crash.
3402 if (Build.VERSION.SDK_INT == 23) {
3403 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3405 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3408 // Reset the image URL variable.
3409 downloadImageUrl = "";
3415 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3416 // Download the image if it has an HTTP or HTTPS URI.
3417 if (imageUrl.startsWith("http")) {
3418 // Get a handle for the system `DOWNLOAD_SERVICE`.
3419 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3421 // Parse `imageUrl`.
3422 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3424 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3425 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3426 if (firstPartyCookiesEnabled) {
3427 // Get the cookies for `imageUrl`.
3428 String cookies = cookieManager.getCookie(imageUrl);
3430 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3431 downloadRequest.addRequestHeader("Cookie", cookies);
3434 // Get the file name from the dialog fragment.
3435 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3436 String imageName = downloadImageNameEditText.getText().toString();
3438 // Specify the download location.
3439 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3440 // Download to the public download directory.
3441 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3442 } else { // External write permission denied.
3443 // Download to the app's external download directory.
3444 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3447 // Allow `MediaScanner` to index the download if it is a media file.
3448 downloadRequest.allowScanningByMediaScanner();
3450 // Add the URL as the description for the download.
3451 downloadRequest.setDescription(imageUrl);
3453 // Show the download notification after the download is completed.
3454 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3456 // Remove the lint warning below that `downloadManager` might be `null`.
3457 assert downloadManager != null;
3459 // Initiate the download.
3460 downloadManager.enqueue(downloadRequest);
3461 } else { // The image is not an HTTP or HTTPS URI.
3462 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3467 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3468 // Download the file if it has an HTTP or HTTPS URI.
3469 if (downloadUrl.startsWith("http")) {
3470 // Get a handle for the system `DOWNLOAD_SERVICE`.
3471 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3473 // Parse `downloadUrl`.
3474 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3476 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3477 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3478 if (firstPartyCookiesEnabled) {
3479 // Get the cookies for `downloadUrl`.
3480 String cookies = cookieManager.getCookie(downloadUrl);
3482 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3483 downloadRequest.addRequestHeader("Cookie", cookies);
3486 // Get the file name from the dialog fragment.
3487 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3488 String fileName = downloadFileNameEditText.getText().toString();
3490 // Specify the download location.
3491 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3492 // Download to the public download directory.
3493 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3494 } else { // External write permission denied.
3495 // Download to the app's external download directory.
3496 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3499 // Allow `MediaScanner` to index the download if it is a media file.
3500 downloadRequest.allowScanningByMediaScanner();
3502 // Add the URL as the description for the download.
3503 downloadRequest.setDescription(downloadUrl);
3505 // Show the download notification after the download is completed.
3506 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3508 // Remove the lint warning below that `downloadManager` might be `null`.
3509 assert downloadManager != null;
3511 // Initiate the download.
3512 downloadManager.enqueue(downloadRequest);
3513 } else { // The download is not an HTTP or HTTPS URI.
3514 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3519 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3520 // Get handles for the views from `dialogFragment`.
3521 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3522 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3523 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3525 // Store the bookmark strings.
3526 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3527 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3529 // Update the bookmark.
3530 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3531 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3532 } else { // Update the bookmark using the `WebView` favorite icon.
3533 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3534 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3535 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3536 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3538 // Update the bookmark and the favorite icon.
3539 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3542 // Update `bookmarksCursor` with the current contents of this folder.
3543 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3545 // Update the `ListView`.
3546 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3550 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3551 // Get handles for the views from `dialogFragment`.
3552 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3553 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3554 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3555 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3557 // Get the new folder name.
3558 String newFolderNameString = editFolderNameEditText.getText().toString();
3560 // Check if the favorite icon has changed.
3561 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3562 // Update the name in the database.
3563 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3564 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3565 // Get the new folder icon `Bitmap`.
3566 Bitmap folderIconBitmap;
3567 if (defaultFolderIconRadioButton.isChecked()) {
3568 // Get the default folder icon and convert it to a `Bitmap`.
3569 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3570 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3571 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3572 } else { // Use the `WebView` favorite icon.
3573 folderIconBitmap = favoriteIconBitmap;
3576 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3577 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3578 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3579 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3581 // Update the folder icon in the database.
3582 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3583 } else { // The folder icon and the name have changed.
3584 // Get the new folder icon `Bitmap`.
3585 Bitmap folderIconBitmap;
3586 if (defaultFolderIconRadioButton.isChecked()) {
3587 // Get the default folder icon and convert it to a `Bitmap`.
3588 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3589 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3590 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3591 } else { // Use the `WebView` favorite icon.
3592 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3595 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3596 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3597 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3598 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3600 // Update the folder name and icon in the database.
3601 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3604 // Update `bookmarksCursor` with the current contents of this folder.
3605 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3607 // Update the `ListView`.
3608 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3612 public void onHttpAuthenticationCancel() {
3613 // Cancel the `HttpAuthHandler`.
3614 httpAuthHandler.cancel();
3618 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3619 // Get handles for the `EditTexts`.
3620 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3621 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3623 // Proceed with the HTTP authentication.
3624 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3627 public void viewSslCertificate(View view) {
3628 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3629 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3630 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3634 public void onSslErrorCancel() {
3635 sslErrorHandler.cancel();
3639 public void onSslErrorProceed() {
3640 sslErrorHandler.proceed();
3644 public void onSslMismatchBack() {
3645 if (mainWebView.canGoBack()) { // There is a back page in the history.
3646 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3647 formattedUrlString = "";
3649 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3650 navigatingHistory = true;
3653 mainWebView.goBack();
3654 } else { // There are no pages to go back to.
3655 // Load a blank page
3661 public void onSslMismatchProceed() {
3662 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3663 ignorePinnedSslCertificate = true;
3667 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3668 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3669 formattedUrlString = "";
3671 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3672 navigatingHistory = true;
3674 // Load the history entry.
3675 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3679 public void onClearHistory() {
3680 // Clear the history.
3681 mainWebView.clearHistory();
3684 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3686 public void onBackPressed() {
3687 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3688 // Close the navigation drawer.
3689 drawerLayout.closeDrawer(GravityCompat.START);
3690 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3691 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3692 // close the bookmarks drawer.
3693 drawerLayout.closeDrawer(GravityCompat.END);
3694 } else { // A subfolder is displayed.
3695 // Place the former parent folder in `currentFolder`.
3696 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3698 // Load the new folder.
3699 loadBookmarksFolder();
3702 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3703 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3704 formattedUrlString = "";
3706 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3707 navigatingHistory = true;
3710 mainWebView.goBack();
3711 } else { // There isn't anything to do in Privacy Browser.
3712 // Pass `onBackPressed()` to the system.
3713 super.onBackPressed();
3717 // 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.
3719 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3720 // File uploads only work on API >= 21.
3721 if (Build.VERSION.SDK_INT >= 21) {
3722 // Pass the file to the WebView.
3723 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3727 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3728 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3729 String unformattedUrlString = urlTextBox.getText().toString().trim();
3731 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3732 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3733 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3734 if (!unformattedUrlString.startsWith("http")) {
3735 unformattedUrlString = "http://" + unformattedUrlString;
3738 // Initialize `unformattedUrl`.
3739 URL unformattedUrl = null;
3741 // 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.
3743 unformattedUrl = new URL(unformattedUrlString);
3744 } catch (MalformedURLException e) {
3745 e.printStackTrace();
3748 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3749 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3750 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3751 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3752 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3753 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3756 Uri.Builder formattedUri = new Uri.Builder();
3757 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3759 // Decode `formattedUri` as a `String` in `UTF-8`.
3760 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3761 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3762 // Load a blank string.
3763 formattedUrlString = "";
3764 } else { // Search for the contents of the URL box.
3765 // Sanitize the search input and convert it to a search.
3766 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3768 // Add the base search URL.
3769 formattedUrlString = searchURL + encodedUrlString;
3772 // 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.
3773 urlTextBox.clearFocus();
3776 loadUrl(formattedUrlString);
3779 private void loadUrl(String url) {// Apply any custom domain settings.
3780 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3781 formattedUrlString = url;
3783 // Apply the domain settings.
3784 applyDomainSettings(url, true, false);
3786 // If loading a website, set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3787 urlIsLoading = !url.equals("");
3790 mainWebView.loadUrl(url, customHeaders);
3793 public void findPreviousOnPage(View view) {
3794 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3795 mainWebView.findNext(false);
3798 public void findNextOnPage(View view) {
3799 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3800 mainWebView.findNext(true);
3803 public void closeFindOnPage(View view) {
3804 // Delete the contents of `find_on_page_edittext`.
3805 findOnPageEditText.setText(null);
3807 // Clear the highlighted phrases.
3808 mainWebView.clearMatches();
3810 // Hide the Find on Page `RelativeLayout`.
3811 findOnPageLinearLayout.setVisibility(View.GONE);
3813 // Show the URL app bar.
3814 supportAppBar.setVisibility(View.VISIBLE);
3816 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3817 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3820 private void applyAppSettings() {
3821 // Get a handle for the shared preferences.
3822 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3824 // Store the values from the shared preferences in variables.
3825 String homepageString = sharedPreferences.getString("homepage", "https://searx.me/");
3826 String torHomepageString = sharedPreferences.getString("tor_homepage", "http://ulrn6sryqaifefld.onion/");
3827 String torSearchString = sharedPreferences.getString("tor_search", "http://ulrn6sryqaifefld.onion/?q=");
3828 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3829 String searchString = sharedPreferences.getString("search", "https://searx.me/?q=");
3830 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3831 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3832 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3833 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3834 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3835 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3836 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3837 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3839 // Set the homepage, search, and proxy options.
3840 if (proxyThroughOrbot) { // Set the Tor options.
3841 // Set `torHomepageString` as `homepage`.
3842 homepage = torHomepageString;
3844 // If formattedUrlString is null assign the homepage to it.
3845 if (formattedUrlString == null) {
3846 formattedUrlString = homepage;
3849 // Set the search URL.
3850 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3851 searchURL = torSearchCustomURLString;
3852 } else { // Use the string from the pre-built list.
3853 searchURL = torSearchString;
3856 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3857 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3859 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3861 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3863 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3866 // Display a message to the user if waiting for Orbot.
3867 if (!orbotStatus.equals("ON")) {
3868 // Set `waitingForOrbot`.
3869 waitingForOrbot = true;
3871 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3872 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3874 } else { // Set the non-Tor options.
3875 // Set `homepageString` as `homepage`.
3876 homepage = homepageString;
3878 // If formattedUrlString is null assign the homepage to it.
3879 if (formattedUrlString == null) {
3880 formattedUrlString = homepage;
3883 // Set the search URL.
3884 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3885 searchURL = searchCustomURLString;
3886 } else { // Use the string from the pre-built list.
3887 searchURL = searchString;
3890 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3891 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3893 // Set the default `appBar` background. `this` refers to the context.
3895 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3897 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3900 // Reset `waitingForOrbot.
3901 waitingForOrbot = false;
3904 // Set Do Not Track status.
3905 if (doNotTrackEnabled) {
3906 customHeaders.put("DNT", "1");
3908 customHeaders.remove("DNT");
3911 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3912 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3913 if (hideSystemBarsOnFullscreen) { // Hide everything.
3914 // Remove the translucent navigation setting if it is currently flagged.
3915 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3917 // Remove the translucent status bar overlay.
3918 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3920 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3921 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3923 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3924 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3925 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3927 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3928 } else { // Hide everything except the status and navigation bars.
3929 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3930 rootCoordinatorLayout.setSystemUiVisibility(0);
3932 // Add the translucent status flag if it is unset.
3933 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3935 if (translucentNavigationBarOnFullscreen) {
3936 // Set the navigation bar to be translucent.
3937 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3939 // Set the navigation bar to be black.
3940 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3943 } else { // Privacy Browser is not in full screen browsing mode.
3944 // 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.
3945 inFullScreenBrowsingMode = false;
3947 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3948 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3952 // Show the `BannerAd` in the free flavor.
3953 if (BuildConfig.FLAVOR.contentEquals("free")) {
3954 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3955 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3958 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3959 rootCoordinatorLayout.setSystemUiVisibility(0);
3961 // Remove the translucent navigation bar flag if it is set.
3962 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3964 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3965 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3967 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3968 rootCoordinatorLayout.setFitsSystemWindows(true);
3972 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3973 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3974 @SuppressWarnings("deprecation")
3975 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3976 // Parse the URL into a URI.
3977 Uri uri = Uri.parse(url);
3979 // Extract the domain from `uri`.
3980 String hostName = uri.getHost();
3982 // Initialize `loadingNewDomainName`.
3983 boolean loadingNewDomainName;
3985 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3986 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3987 //noinspection SimplifiableIfStatement
3988 if ((hostName == null) || (currentDomainName == null)) {
3989 loadingNewDomainName = true;
3990 } else { // Determine if `hostName` equals `currentDomainName`.
3991 loadingNewDomainName = !hostName.equals(currentDomainName);
3994 // Strings don't like to be null.
3995 if (hostName == null) {
3999 // 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.
4000 if (loadingNewDomainName) {
4001 // Set the new `hostname` as the `currentDomainName`.
4002 currentDomainName = hostName;
4004 // Reset `ignorePinnedSslCertificate`.
4005 ignorePinnedSslCertificate = false;
4007 // Reset the favorite icon if specified.
4008 if (resetFavoriteIcon) {
4009 favoriteIconBitmap = favoriteIconDefaultBitmap;
4010 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
4013 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
4014 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
4015 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
4017 // Get a full cursor from `domainsDatabaseHelper`.
4018 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
4020 // Initialize `domainSettingsSet`.
4021 Set<String> domainSettingsSet = new HashSet<>();
4023 // Get the domain name column index.
4024 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
4026 // Populate `domainSettingsSet`.
4027 for (int i = 0; i < domainNameCursor.getCount(); i++) {
4028 // Move `domainsCursor` to the current row.
4029 domainNameCursor.moveToPosition(i);
4031 // Store the domain name in `domainSettingsSet`.
4032 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
4035 // Close `domainNameCursor.
4036 domainNameCursor.close();
4038 // Initialize variables to track if domain settings will be applied and, if so, under which name.
4039 domainSettingsApplied = false;
4040 String domainNameInDatabase = null;
4042 // Check the hostname.
4043 if (domainSettingsSet.contains(hostName)) {
4044 domainSettingsApplied = true;
4045 domainNameInDatabase = hostName;
4048 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
4049 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
4050 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
4051 // Apply the domain settings.
4052 domainSettingsApplied = true;
4054 // Store the applied domain names as it appears in the database.
4055 domainNameInDatabase = "*." + hostName;
4058 // Strip out the lowest subdomain of of the host name.
4059 hostName = hostName.substring(hostName.indexOf(".") + 1);
4063 // Get a handle for the shared preference.
4064 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4066 // Store the general preference information.
4067 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
4068 String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
4069 defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
4070 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
4071 nightMode = sharedPreferences.getBoolean("night_mode", false);
4073 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
4074 // Get a cursor for the current host and move it to the first position.
4075 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
4076 currentHostDomainSettingsCursor.moveToFirst();
4078 // Get the settings from the cursor.
4079 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
4080 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
4081 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
4082 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
4083 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
4084 // Form data can be removed once the minimum API >= 26.
4085 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
4086 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
4087 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
4088 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
4089 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
4090 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
4091 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
4092 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
4093 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
4094 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
4095 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
4096 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
4097 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
4098 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
4099 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
4100 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
4101 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
4102 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
4103 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
4105 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
4106 switch (nightModeInt) {
4107 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
4111 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
4116 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4118 javaScriptEnabled = true;
4121 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
4122 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
4123 pinnedDomainSslStartDate = null;
4125 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
4128 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
4129 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
4130 pinnedDomainSslEndDate = null;
4132 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
4135 // Close `currentHostDomainSettingsCursor`.
4136 currentHostDomainSettingsCursor.close();
4138 // Apply the domain settings.
4139 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4140 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4141 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4143 // Apply the form data setting if the API < 26.
4144 if (Build.VERSION.SDK_INT < 26) {
4145 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4148 // Apply the font size.
4149 if (fontSize == 0) { // Apply the default font size.
4150 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4151 } else { // Apply the specified font size.
4152 mainWebView.getSettings().setTextZoom(fontSize);
4155 // Set third-party cookies status if API >= 21.
4156 if (Build.VERSION.SDK_INT >= 21) {
4157 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4160 // 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.
4161 // <https://redmine.stoutner.com/issues/160>
4162 if (!urlIsLoading) {
4163 // Set the user agent.
4164 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4165 // Get the array position of the default user agent name.
4166 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4168 // Set the user agent according to the system default.
4169 switch (defaultUserAgentArrayPosition) {
4170 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4171 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4172 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4175 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4176 // Set the user agent to `""`, which uses the default value.
4177 mainWebView.getSettings().setUserAgentString("");
4180 case SETTINGS_CUSTOM_USER_AGENT:
4181 // Set the custom user agent.
4182 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4186 // Get the user agent string from the user agent data array
4187 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4189 } else { // Set the user agent according to the stored name.
4190 // Get the array position of the user agent name.
4191 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4193 switch (userAgentArrayPosition) {
4194 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4195 mainWebView.getSettings().setUserAgentString(userAgentName);
4198 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4199 // Set the user agent to `""`, which uses the default value.
4200 mainWebView.getSettings().setUserAgentString("");
4204 // Get the user agent string from the user agent data array.
4205 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4209 // Set swipe to refresh.
4210 switch (swipeToRefreshInt) {
4211 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
4212 // Set swipe to refresh according to the default.
4213 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4216 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
4217 // Enable swipe to refresh.
4218 swipeRefreshLayout.setEnabled(true);
4221 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
4222 // Disable swipe to refresh.
4223 swipeRefreshLayout.setEnabled(false);
4226 // Store the applied user agent string, which is used in the View Source activity.
4227 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4230 // 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.
4232 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4234 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4236 } else { // The new URL does not have custom domain settings. Load the defaults.
4237 // Store the values from `sharedPreferences` in variables.
4238 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
4239 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
4240 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
4241 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
4242 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false); // Form data can be removed once the minimum API >= 26.
4243 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
4244 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
4245 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
4246 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
4247 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
4248 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
4250 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4252 javaScriptEnabled = true;
4255 // Apply the default settings.
4256 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4257 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4258 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4259 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4260 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4262 // Apply the form data setting if the API < 26.
4263 if (Build.VERSION.SDK_INT < 26) {
4264 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4267 // Reset the pinned SSL certificate information.
4268 domainSettingsDatabaseId = -1;
4269 pinnedDomainSslCertificate = false;
4270 pinnedDomainSslIssuedToCNameString = "";
4271 pinnedDomainSslIssuedToONameString = "";
4272 pinnedDomainSslIssuedToUNameString = "";
4273 pinnedDomainSslIssuedByCNameString = "";
4274 pinnedDomainSslIssuedByONameString = "";
4275 pinnedDomainSslIssuedByUNameString = "";
4276 pinnedDomainSslStartDate = null;
4277 pinnedDomainSslEndDate = null;
4279 // Set third-party cookies status if API >= 21.
4280 if (Build.VERSION.SDK_INT >= 21) {
4281 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4284 // 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.
4285 // <https://redmine.stoutner.com/issues/160>
4286 if (!urlIsLoading) {
4287 // Get the array position of the user agent name.
4288 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4290 // Set the user agent.
4291 switch (userAgentArrayPosition) {
4292 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4293 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4294 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4297 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4298 // Set the user agent to `""`, which uses the default value.
4299 mainWebView.getSettings().setUserAgentString("");
4302 case SETTINGS_CUSTOM_USER_AGENT:
4303 // Set the custom user agent.
4304 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4308 // Get the user agent string from the user agent data array
4309 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4312 // Store the applied user agent string, which is used in the View Source activity.
4313 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4316 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4317 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4320 // Close `domainsDatabaseHelper`.
4321 domainsDatabaseHelper.close();
4323 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
4324 onTheFlyDisplayImagesSet = false;
4325 setDisplayWebpageImages();
4327 // Update the privacy icons, but only if `mainMenu` has already been populated.
4328 if (mainMenu != null) {
4329 updatePrivacyIcons(true);
4333 // Reload the website if returning from the Domains activity.
4334 if (reloadWebsite) {
4335 mainWebView.reload();
4339 private void setDisplayWebpageImages() {
4340 if (!onTheFlyDisplayImagesSet) {
4341 if (domainSettingsApplied) { // Custom domain settings are applied.
4342 switch (displayWebpageImagesInt) {
4343 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4344 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4347 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4348 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4351 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4352 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4355 } else { // Default settings are applied.
4356 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4361 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4362 // Get handles for the menu items.
4363 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4364 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4365 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4366 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4368 // Update the privacy icon.
4369 if (javaScriptEnabled) { // JavaScript is enabled.
4370 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4371 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4372 privacyMenuItem.setIcon(R.drawable.warning);
4373 } else { // All the dangerous features are disabled.
4374 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4377 // Update the first-party cookies icon.
4378 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4379 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4380 } else { // First-party cookies are disabled.
4382 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4384 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4388 // Update the DOM storage icon.
4389 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4390 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4391 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4393 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4395 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4397 } else { // JavaScript is disabled, so DOM storage is ghosted.
4399 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4401 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4405 // Update the refresh icon.
4407 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4409 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4412 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4413 if (runInvalidateOptionsMenu) {
4414 invalidateOptionsMenu();
4418 private void highlightUrlText() {
4419 String urlString = urlTextBox.getText().toString();
4421 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4422 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4423 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4424 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4427 // Get the index of the `/` immediately after the domain name.
4428 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4430 // De-emphasize the text after the domain name.
4431 if (endOfDomainName > 0) {
4432 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4436 private void loadBookmarksFolder() {
4437 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4438 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4440 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4441 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4443 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4444 // Inflate the individual item layout. `false` does not attach it to the root.
4445 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4449 public void bindView(View view, Context context, Cursor cursor) {
4450 // Get handles for the views.
4451 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4452 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4454 // Get the favorite icon byte array from the cursor.
4455 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4457 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4458 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4460 // Display the bitmap in `bookmarkFavoriteIcon`.
4461 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4463 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4464 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4465 bookmarkNameTextView.setText(bookmarkNameString);
4467 // Make the font bold for folders.
4468 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4469 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4470 } else { // Reset the font to default for normal bookmarks.
4471 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4476 // Populate the `ListView` with the adapter.
4477 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4479 // Set the bookmarks drawer title.
4480 if (currentBookmarksFolder.isEmpty()) {
4481 bookmarksTitleTextView.setText(R.string.bookmarks);
4483 bookmarksTitleTextView.setText(currentBookmarksFolder);