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()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, 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 // `domainSettingsJavaScriptEnabled` is used in `onOptionsItemSelected()` and `applyDomainSettings()`.
417 private Boolean domainSettingsJavaScriptEnabled;
419 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
420 private int displayWebpageImagesInt;
422 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
423 private boolean onTheFlyDisplayImagesSet;
425 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
426 private String waitingForOrbotHTMLString;
428 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
429 private String privateDataDirectoryString;
431 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
432 private LinearLayout findOnPageLinearLayout;
434 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
435 private EditText findOnPageEditText;
437 // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
438 private boolean displayAdditionalAppBarIcons;
440 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
441 private ActionBarDrawerToggle drawerToggle;
443 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
444 private Toolbar supportAppBar;
446 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
447 private EditText urlTextBox;
449 // The color spans are used in `onCreate()` and `highlightUrlText()`.
450 private ForegroundColorSpan redColorSpan;
451 private ForegroundColorSpan initialGrayColorSpan;
452 private ForegroundColorSpan finalGrayColorSpan;
454 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
455 private SslErrorHandler sslErrorHandler;
457 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
458 private static HttpAuthHandler httpAuthHandler;
460 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
461 private InputMethodManager inputMethodManager;
463 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
464 private RelativeLayout mainWebViewRelativeLayout;
466 // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
467 private boolean urlIsLoading;
469 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
470 private boolean pinnedDomainSslCertificate;
472 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
473 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
475 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
476 private ListView bookmarksListView;
478 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
479 private TextView bookmarksTitleTextView;
481 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
482 private Cursor bookmarksCursor;
484 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
485 private CursorAdapter bookmarksCursorAdapter;
487 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
488 private String oldFolderNameString;
490 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
491 private ValueCallback<Uri[]> fileChooserCallback;
493 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
494 private String downloadUrl;
495 private String downloadContentDisposition;
496 private long downloadContentLength;
498 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
499 private String downloadImageUrl;
501 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
502 private ArrayAdapter<CharSequence> userAgentNamesArray;
503 private String[] userAgentDataArray;
505 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
506 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
507 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
510 // 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.
511 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
512 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
513 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
514 @SuppressWarnings("deprecation")
515 protected void onCreate(Bundle savedInstanceState) {
516 // Get a handle for the shared preferences.
517 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
519 // Get the theme and screenshot preferences.
520 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
521 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
523 // Disable screenshots if not allowed.
524 if (!allowScreenshots) {
525 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
528 // Set the activity theme.
530 setTheme(R.style.PrivacyBrowserDark);
532 setTheme(R.style.PrivacyBrowserLight);
535 // Run the default commands.
536 super.onCreate(savedInstanceState);
538 // Set the content view.
539 setContentView(R.layout.main_drawerlayout);
541 // Get a handle for `inputMethodManager`.
542 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
544 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
545 supportAppBar = findViewById(R.id.app_bar);
546 setSupportActionBar(supportAppBar);
547 appBar = getSupportActionBar();
549 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
550 assert appBar != null;
552 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
553 appBar.setCustomView(R.layout.url_app_bar);
554 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
556 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
557 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
558 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
559 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
561 // Get a handle for `urlTextBox`.
562 urlTextBox = findViewById(R.id.url_edittext);
564 // Remove the formatting from `urlTextBar` when the user is editing the text.
565 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
566 if (hasFocus) { // The user is editing `urlTextBox`.
567 // Remove the highlighting.
568 urlTextBox.getText().removeSpan(redColorSpan);
569 urlTextBox.getText().removeSpan(initialGrayColorSpan);
570 urlTextBox.getText().removeSpan(finalGrayColorSpan);
571 } else { // The user has stopped editing `urlTextBox`.
572 // Reapply the highlighting.
577 // Set the go button on the keyboard to load the URL in `urlTextBox`.
578 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
579 // If the event is a key-down event on the `enter` button, load the URL.
580 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
581 // Load the URL into the mainWebView and consume the event.
583 loadUrlFromTextBox();
584 } catch (UnsupportedEncodingException e) {
587 // If the enter key was pressed, consume the event.
590 // If any other key was pressed, do not consume the event.
595 // Set `waitingForOrbotHTMLString`.
596 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
598 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
599 currentDomainName = "";
600 orbotStatus = "unknown";
601 waitingForOrbot = false;
603 // Create an Orbot status `BroadcastReceiver`.
604 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
606 public void onReceive(Context context, Intent intent) {
607 // Store the content of the status message in `orbotStatus`.
608 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
610 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
611 if (orbotStatus.equals("ON") && waitingForOrbot) {
612 // Reset `waitingForOrbot`.
613 waitingForOrbot = false;
615 // Load `formattedUrlString
616 loadUrl(formattedUrlString);
621 // Register `orbotStatusBroadcastReceiver` on `this` context.
622 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
624 // Get handles for views that need to be accessed.
625 drawerLayout = findViewById(R.id.drawerlayout);
626 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
627 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
628 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
629 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
630 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
631 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
632 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
633 mainWebView = findViewById(R.id.main_webview);
634 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
635 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
636 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
637 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
638 favoriteIconImageView = findViewById(R.id.favorite_icon);
640 // 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.
642 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
643 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
644 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
645 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
647 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
648 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
649 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
650 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
653 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
654 launchBookmarksActivityFab.setOnClickListener(v -> {
655 // Create an intent to launch the bookmarks activity.
656 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
658 // Include the current folder with the `Intent`.
659 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
662 startActivity(bookmarksIntent);
665 // Set the create new bookmark folder FAB to display an alert dialog.
666 createBookmarkFolderFab.setOnClickListener(v -> {
667 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
668 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
669 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
672 // Set the create new bookmark FAB to display an alert dialog.
673 createBookmarkFab.setOnClickListener(view -> {
674 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
675 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
676 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
679 // Create a double-tap listener to toggle full-screen mode.
680 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
681 // Override `onDoubleTap()`. All other events are handled using the default settings.
683 public boolean onDoubleTap(MotionEvent event) {
684 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
685 // Toggle `inFullScreenBrowsingMode`.
686 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
688 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
689 // Hide the `appBar`.
692 // Hide the banner ad in the free flavor.
693 if (BuildConfig.FLAVOR.contentEquals("free")) {
694 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
695 AdHelper.hideAd(findViewById(R.id.adview));
698 // Modify the system bars.
699 if (hideSystemBarsOnFullscreen) { // Hide everything.
700 // Remove the translucent overlays.
701 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
703 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
704 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
706 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
707 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
708 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
710 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
712 // Set `rootCoordinatorLayout` to fill the whole screen.
713 rootCoordinatorLayout.setFitsSystemWindows(false);
714 } else { // Hide everything except the status and navigation bars.
715 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
716 rootCoordinatorLayout.setFitsSystemWindows(false);
718 // 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.
719 if (translucentNavigationBarOnFullscreen) {
720 // Set the navigation bar to be translucent.
721 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
724 } else { // Switch to normal viewing mode.
725 // Show the `appBar`.
728 // Show the `BannerAd` in the free flavor.
729 if (BuildConfig.FLAVOR.contentEquals("free")) {
730 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
731 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
734 // Remove the translucent navigation bar flag if it is set.
735 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
737 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
738 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
740 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
741 rootCoordinatorLayout.setSystemUiVisibility(0);
743 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
744 rootCoordinatorLayout.setFitsSystemWindows(true);
747 // Consume the double-tap.
749 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
755 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
756 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
757 // Call `performClick()` on the view, which is required for accessibility.
760 // Send the `event` to `gestureDetector`.
761 return gestureDetector.onTouchEvent(event);
764 // Update `findOnPageCountTextView`.
765 mainWebView.setFindListener(new WebView.FindListener() {
766 // Get a handle for `findOnPageCountTextView`.
767 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
770 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
771 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
772 // Set `findOnPageCountTextView` to `0/0`.
773 findOnPageCountTextView.setText(R.string.zero_of_zero);
774 } else if (isDoneCounting) { // There are matches.
775 // `activeMatchOrdinal` is zero-based.
776 int activeMatch = activeMatchOrdinal + 1;
778 // Build the match string.
779 String matchString = activeMatch + "/" + numberOfMatches;
781 // Set `findOnPageCountTextView`.
782 findOnPageCountTextView.setText(matchString);
787 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
788 findOnPageEditText.addTextChangedListener(new TextWatcher() {
790 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
795 public void onTextChanged(CharSequence s, int start, int before, int count) {
800 public void afterTextChanged(Editable s) {
801 // Search for the text in `mainWebView`.
802 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
806 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
807 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
808 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
809 // Hide the soft keyboard. `0` indicates no additional flags.
810 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
812 // Consume the event.
814 } else { // A different key was pressed.
815 // Do not consume the event.
820 // Implement swipe to refresh
821 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
822 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
823 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
825 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
826 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
827 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
829 // Listen for touches on the navigation menu.
830 final NavigationView navigationView = findViewById(R.id.navigationview);
831 navigationView.setNavigationItemSelectedListener(this);
833 // 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.
834 final Menu navigationMenu = navigationView.getMenu();
835 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
836 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
837 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
838 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
840 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
841 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
842 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
844 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
845 currentBookmarksFolder = "";
847 // Load the home folder, which is `""` in the database.
848 loadBookmarksFolder();
850 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
851 // Convert the id from long to int to match the format of the bookmarks database.
852 int databaseID = (int) id;
854 // Get the bookmark cursor for this ID and move it to the first row.
855 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
856 bookmarkCursor.moveToFirst();
858 // Act upon the bookmark according to the type.
859 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
860 // Store the new folder name in `currentBookmarksFolder`.
861 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
863 // Load the new folder.
864 loadBookmarksFolder();
865 } else { // The selected bookmark is not a folder.
866 // Load the bookmark URL.
867 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
869 // Close the bookmarks drawer.
870 drawerLayout.closeDrawer(GravityCompat.END);
873 // Close the `Cursor`.
874 bookmarkCursor.close();
877 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
878 // Convert the database ID from `long` to `int`.
879 int databaseId = (int) id;
881 // Find out if the selected bookmark is a folder.
882 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
885 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
886 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
888 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
889 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
890 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
892 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
893 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
894 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
897 // Consume the event.
901 // The drawer listener is used to update the navigation menu.
902 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
904 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
908 public void onDrawerOpened(@NonNull View drawerView) {
912 public void onDrawerClosed(@NonNull View drawerView) {
916 public void onDrawerStateChanged(int newState) {
917 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
918 // Update the back, forward, history, and requests menu items.
919 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
920 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
921 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
922 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
924 // Hide the keyboard (if displayed).
925 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
927 // Clear the focus from from the URL text box.
928 urlTextBox.clearFocus();
933 // drawerToggle creates the hamburger icon at the start of the AppBar.
934 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
936 // Get a handle for the progress bar.
937 final ProgressBar progressBar = findViewById(R.id.progress_bar);
939 mainWebView.setWebChromeClient(new WebChromeClient() {
940 // Update the progress bar when a page is loading.
942 public void onProgressChanged(WebView view, int progress) {
943 // Inject the night mode CSS if night mode is enabled.
945 // `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
946 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
947 // `border: none` removes all borders, which can also be used to underline text.
948 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
949 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
950 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
951 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
952 // Initialize a `Handler` to display `mainWebView`.
953 Handler displayWebViewHandler = new Handler();
955 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
956 Runnable displayWebViewRunnable = () -> {
957 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
958 if (progressBar.getVisibility() == View.GONE) {
959 mainWebView.setVisibility(View.VISIBLE);
963 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
964 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
968 // Update the progress bar.
969 progressBar.setProgress(progress);
971 // Set the visibility of the progress bar.
972 if (progress < 100) {
973 // Show the progress bar.
974 progressBar.setVisibility(View.VISIBLE);
976 // Hide the progress bar.
977 progressBar.setVisibility(View.GONE);
979 // Display `mainWebView` if night mode is disabled.
980 // 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
981 // currently enabled.
983 mainWebView.setVisibility(View.VISIBLE);
986 //Stop the swipe to refresh indicator if it is running
987 swipeRefreshLayout.setRefreshing(false);
991 // Set the favorite icon when it changes.
993 public void onReceivedIcon(WebView view, Bitmap icon) {
994 // Only update the favorite icon if the website has finished loading.
995 if (progressBar.getVisibility() == View.GONE) {
996 // Save a copy of the favorite icon.
997 favoriteIconBitmap = icon;
999 // Place the favorite icon in the appBar.
1000 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1004 // Save a copy of the title when it changes.
1006 public void onReceivedTitle(WebView view, String title) {
1007 // Save a copy of the title.
1008 webViewTitle = title;
1011 // Enter full screen video.
1013 public void onShowCustomView(View view, CustomViewCallback callback) {
1014 // Set the full screen video flag.
1015 displayingFullScreenVideo = true;
1017 // Pause the ad if this is the free flavor.
1018 if (BuildConfig.FLAVOR.contentEquals("free")) {
1019 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1020 AdHelper.pauseAd(findViewById(R.id.adview));
1023 // Remove the translucent overlays.
1024 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1026 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1027 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1029 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1030 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1031 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1033 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1035 // Set `rootCoordinatorLayout` to fill the entire screen.
1036 rootCoordinatorLayout.setFitsSystemWindows(false);
1038 // Disable the sliding drawers.
1039 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1041 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1042 fullScreenVideoFrameLayout.addView(view);
1043 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1046 // Exit full screen video.
1048 public void onHideCustomView() {
1049 // Unset the full screen video flag.
1050 displayingFullScreenVideo = false;
1052 // Hide `fullScreenVideoFrameLayout`.
1053 fullScreenVideoFrameLayout.removeAllViews();
1054 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1056 // Enable the sliding drawers.
1057 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1059 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1060 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1061 if (hideSystemBarsOnFullscreen) { // Hide everything.
1062 // Remove the translucent navigation setting if it is currently flagged.
1063 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1065 // Remove the translucent status bar overlay.
1066 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1068 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1069 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1071 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1072 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1073 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1075 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1076 } else { // Hide everything except the status and navigation bars.
1077 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1078 rootCoordinatorLayout.setSystemUiVisibility(0);
1080 // Add the translucent status flag if it is unset.
1081 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1083 if (translucentNavigationBarOnFullscreen) {
1084 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1085 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1087 // Set the navigation bar to be black.
1088 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1091 } else { // Switch to normal viewing mode.
1092 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1093 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1097 // Show the `BannerAd` in the free flavor.
1098 if (BuildConfig.FLAVOR.contentEquals("free")) {
1099 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1100 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1103 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1104 rootCoordinatorLayout.setSystemUiVisibility(0);
1106 // Remove the translucent navigation bar flag if it is set.
1107 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1109 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1110 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1112 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1113 rootCoordinatorLayout.setFitsSystemWindows(true);
1116 // Show the ad if this is the free flavor.
1117 if (BuildConfig.FLAVOR.contentEquals("free")) {
1118 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1119 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1125 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1126 // Show the file chooser if the device is running API >= 21.
1127 if (Build.VERSION.SDK_INT >= 21) {
1128 // Store the file path callback.
1129 fileChooserCallback = filePathCallback;
1131 // Create an intent to open a chooser based ont the file chooser parameters.
1132 Intent fileChooserIntent = fileChooserParams.createIntent();
1134 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1135 startActivityForResult(fileChooserIntent, 0);
1141 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1142 registerForContextMenu(mainWebView);
1144 // Allow the downloading of files.
1145 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1146 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1147 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1148 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1150 // Store the variables for future use by `onRequestPermissionsResult()`.
1152 downloadContentDisposition = contentDisposition;
1153 downloadContentLength = contentLength;
1155 // Show a dialog if the user has previously denied the permission.
1156 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1157 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1158 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1160 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1161 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1162 } else { // Show the permission request directly.
1163 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1164 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1166 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1167 // Get a handle for the download file alert dialog.
1168 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1170 // Show the download file alert dialog.
1171 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1175 // Allow pinch to zoom.
1176 mainWebView.getSettings().setBuiltInZoomControls(true);
1178 // Hide zoom controls.
1179 mainWebView.getSettings().setDisplayZoomControls(false);
1181 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1182 mainWebView.getSettings().setUseWideViewPort(true);
1184 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1185 mainWebView.getSettings().setLoadWithOverviewMode(true);
1187 // Explicitly disable geolocation.
1188 mainWebView.getSettings().setGeolocationEnabled(false);
1190 // Initialize cookieManager.
1191 cookieManager = CookieManager.getInstance();
1193 // 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).
1194 customHeaders.put("X-Requested-With", "");
1196 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1197 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1199 // Get the intent that started the app.
1200 final Intent launchingIntent = getIntent();
1202 // Extract the launching intent data as `launchingIntentUriData`.
1203 final Uri launchingIntentUriData = launchingIntent.getData();
1205 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1206 if (launchingIntentUriData != null) {
1207 formattedUrlString = launchingIntentUriData.toString();
1210 // Get a handle for the `Runtime`.
1211 privacyBrowserRuntime = Runtime.getRuntime();
1213 // Store the application's private data directory.
1214 privateDataDirectoryString = getApplicationInfo().dataDir;
1215 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1217 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1218 inFullScreenBrowsingMode = false;
1220 // Initialize the privacy settings variables.
1221 javaScriptEnabled = false;
1222 firstPartyCookiesEnabled = false;
1223 thirdPartyCookiesEnabled = false;
1224 domStorageEnabled = false;
1225 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1228 // Store the default user agent.
1229 webViewDefaultUserAgent = mainWebView.getSettings().getUserAgentString();
1231 // Initialize the WebView title.
1232 webViewTitle = getString(R.string.no_title);
1234 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1235 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1236 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1237 assert favoriteIconBitmapDrawable != null;
1238 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1240 // If the favorite icon is null, load the default.
1241 if (favoriteIconBitmap == null) {
1242 favoriteIconBitmap = favoriteIconDefaultBitmap;
1245 // Initialize the user agent array adapter and string array.
1246 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1247 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1249 // Apply the app settings from the shared preferences.
1252 // Instantiate the block list helper.
1253 BlockListHelper blockListHelper = new BlockListHelper();
1255 // Initialize the list of resource requests.
1256 resourceRequests = new ArrayList<>();
1258 // Parse the block lists.
1259 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1260 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1261 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1262 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1263 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1265 // Store the list versions.
1266 easyListVersion = easyList.get(0).get(0)[0];
1267 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1268 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1269 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1270 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1272 // Get a handle for the activity. This is used to update the requests counter while the navigation menu is open.
1273 Activity activity = this;
1275 mainWebView.setWebViewClient(new WebViewClient() {
1276 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1277 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1278 @SuppressWarnings("deprecation")
1280 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1281 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1282 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1283 formattedUrlString = "";
1285 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1286 applyDomainSettings(url, true, false);
1288 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1290 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1291 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1292 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1294 // Parse the url and set it as the data for the intent.
1295 emailIntent.setData(Uri.parse(url));
1297 // Open the email program in a new task instead of as part of Privacy Browser.
1298 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1301 startActivity(emailIntent);
1303 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1305 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1306 // Open the dialer and load the phone number, but wait for the user to place the call.
1307 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1309 // Add the phone number to the intent.
1310 dialIntent.setData(Uri.parse(url));
1312 // Open the dialer in a new task instead of as part of Privacy Browser.
1313 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1316 startActivity(dialIntent);
1318 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1320 } else { // Load a system chooser to select an app that can handle the URL.
1321 // Open an app that can handle the URL.
1322 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1324 // Add the URL to the intent.
1325 genericIntent.setData(Uri.parse(url));
1327 // List all apps that can handle the URL instead of just opening the first one.
1328 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1330 // Open the app in a new task instead of as part of Privacy Browser.
1331 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1333 // Start the app or display a snackbar if no app is available to handle the URL.
1335 startActivity(genericIntent);
1336 } catch (ActivityNotFoundException exception) {
1337 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1340 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1345 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1346 @SuppressWarnings("deprecation")
1348 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1349 // Create an empty web resource response to be used if the resource request is blocked.
1350 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1352 // Reset the whitelist results tracker.
1353 whiteListResultStringArray = null;
1355 // Initialize the third party request tracker.
1356 boolean isThirdPartyRequest = false;
1358 // Initialize the current domain string.
1359 String currentDomain = "";
1361 // Nobody is happy when comparing null strings.
1362 if (!(formattedUrlString == null) && !(url == null)) {
1363 // Get the domain strings to URIs.
1364 Uri currentDomainUri = Uri.parse(formattedUrlString);
1365 Uri requestDomainUri = Uri.parse(url);
1367 // Get the domain host names.
1368 String currentBaseDomain = currentDomainUri.getHost();
1369 String requestBaseDomain = requestDomainUri.getHost();
1371 // Update the current domain variable.
1372 currentDomain = currentBaseDomain;
1374 // Only compare the current base domain and the request base domain if neither is null.
1375 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1376 // Determine the current base domain.
1377 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1378 // Remove the first subdomain.
1379 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1382 // Determine the request base domain.
1383 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1384 // Remove the first subdomain.
1385 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1388 // Update the third party request tracker.
1389 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1393 // Block third-party requests if enabled.
1394 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1395 // Increment the blocked requests counters.
1397 thirdPartyBlockedRequests++;
1399 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1400 activity.runOnUiThread(() -> {
1401 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1402 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1403 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1406 // Add the request to the log.
1407 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1409 // Return an empty web resource response.
1410 return emptyWebResourceResponse;
1413 // Check UltraPrivacy if it is enabled.
1414 if (ultraPrivacyEnabled) {
1415 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1416 // Increment the blocked requests counters.
1418 ultraPrivacyBlockedRequests++;
1420 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1421 activity.runOnUiThread(() -> {
1422 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1423 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1424 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1427 // The resource request was blocked. Return an empty web resource response.
1428 return emptyWebResourceResponse;
1431 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1432 if (whiteListResultStringArray != null) {
1433 // Add a whitelist entry to the resource requests array.
1434 resourceRequests.add(whiteListResultStringArray);
1436 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1441 // Check EasyList if it is enabled.
1442 if (easyListEnabled) {
1443 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1444 // Increment the blocked requests counters.
1446 easyListBlockedRequests++;
1448 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1449 activity.runOnUiThread(() -> {
1450 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1451 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1452 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1455 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1456 whiteListResultStringArray = null;
1458 // The resource request was blocked. Return an empty web resource response.
1459 return emptyWebResourceResponse;
1463 // Check EasyPrivacy if it is enabled.
1464 if (easyPrivacyEnabled) {
1465 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1466 // Increment the blocked requests counters.
1468 easyPrivacyBlockedRequests++;
1470 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1471 activity.runOnUiThread(() -> {
1472 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1473 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1474 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1477 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1478 whiteListResultStringArray = null;
1480 // The resource request was blocked. Return an empty web resource response.
1481 return emptyWebResourceResponse;
1485 // Check Fanboy’s Annoyance List if it is enabled.
1486 if (fanboysAnnoyanceListEnabled) {
1487 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1488 // Increment the blocked requests counters.
1490 fanboysAnnoyanceListBlockedRequests++;
1492 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1493 activity.runOnUiThread(() -> {
1494 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1495 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1496 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1499 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1500 whiteListResultStringArray = null;
1502 // The resource request was blocked. Return an empty web resource response.
1503 return emptyWebResourceResponse;
1505 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1506 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1507 // Increment the blocked requests counters.
1509 fanboysSocialBlockingListBlockedRequests++;
1511 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1512 activity.runOnUiThread(() -> {
1513 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1514 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1515 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1518 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1519 whiteListResultStringArray = null;
1521 // The resource request was blocked. Return an empty web resource response.
1522 return emptyWebResourceResponse;
1526 // Add the request to the log because it hasn't been processed by any of the previous checks.
1527 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1528 resourceRequests.add(whiteListResultStringArray);
1529 } else { // The request didn't match any blocklist entry. Log it as a defult request.
1530 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1533 // The resource request has not been blocked. `return null` loads the requested resource.
1537 // Handle HTTP authentication requests.
1539 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1540 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1541 httpAuthHandler = handler;
1543 // Display the HTTP authentication dialog.
1544 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1545 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1548 // Update the URL in urlTextBox when the page starts to load.
1550 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1551 // Reset the list of resource requests.
1552 resourceRequests.clear();
1554 // Initialize the counters for requests blocked by each blocklist.
1555 blockedRequests = 0;
1556 easyListBlockedRequests = 0;
1557 easyPrivacyBlockedRequests = 0;
1558 fanboysAnnoyanceListBlockedRequests = 0;
1559 fanboysSocialBlockingListBlockedRequests = 0;
1560 ultraPrivacyBlockedRequests = 0;
1561 thirdPartyBlockedRequests = 0;
1563 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1565 mainWebView.setVisibility(View.INVISIBLE);
1568 // Hide the keyboard. `0` indicates no additional flags.
1569 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1571 // Check to see if Privacy Browser is waiting on Orbot.
1572 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1573 // 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.
1574 formattedUrlString = url;
1576 // Display the formatted URL text.
1577 urlTextBox.setText(formattedUrlString);
1579 // Apply text highlighting to `urlTextBox`.
1582 // Apply any custom domain settings if the URL was loaded by navigating history.
1583 if (navigatingHistory) {
1584 // Reset `navigatingHistory`.
1585 navigatingHistory = false;
1587 // Apply the domain settings.
1588 applyDomainSettings(url, true, false);
1591 // 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.
1592 urlIsLoading = true;
1594 // Replace Refresh with Stop if the menu item has been created. (The WebView typically begins loading before the menu items are instantiated.)
1595 if (refreshMenuItem != null) {
1597 refreshMenuItem.setTitle(R.string.stop);
1599 // If the icon is displayed in the AppBar, set it according to the theme.
1600 if (displayAdditionalAppBarIcons) {
1602 refreshMenuItem.setIcon(R.drawable.close_dark);
1604 refreshMenuItem.setIcon(R.drawable.close_light);
1611 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1613 public void onPageFinished(WebView view, String url) {
1614 // Reset the wide view port if it has been turned off by the waiting for Orbot message.
1615 if (!waitingForOrbot) {
1616 mainWebView.getSettings().setUseWideViewPort(true);
1619 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1620 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1621 cookieManager.flush();
1624 // Update the Refresh menu item if it has been created.
1625 if (refreshMenuItem != null) {
1626 // Reset the Refresh title.
1627 refreshMenuItem.setTitle(R.string.refresh);
1629 // If the icon is displayed in the AppBar, reset it according to the theme.
1630 if (displayAdditionalAppBarIcons) {
1632 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1634 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1639 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1640 urlIsLoading = false;
1642 // Clear the cache and history if Incognito Mode is enabled.
1643 if (incognitoModeEnabled) {
1644 // Clear the cache. `true` includes disk files.
1645 mainWebView.clearCache(true);
1647 // Clear the back/forward history.
1648 mainWebView.clearHistory();
1650 // Manually delete cache folders.
1652 // Delete the main cache directory.
1653 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1655 // Delete the secondary `Service Worker` cache directory.
1656 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1657 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1658 } catch (IOException e) {
1659 // Do nothing if an error is thrown.
1663 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1664 if (!waitingForOrbot) {
1665 // Check to see if `WebView` has set `url` to be `about:blank`.
1666 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1667 // Set `formattedUrlString` to `""`.
1668 formattedUrlString = "";
1670 urlTextBox.setText(formattedUrlString);
1672 // Request focus for `urlTextBox`.
1673 urlTextBox.requestFocus();
1675 // Display the keyboard.
1676 inputMethodManager.showSoftInput(urlTextBox, 0);
1678 // Apply the domain settings. This clears any settings from the previous domain.
1679 applyDomainSettings(formattedUrlString, true, false);
1680 } else { // `WebView` has loaded a webpage.
1681 // Set `formattedUrlString`.
1682 formattedUrlString = url;
1684 // Only update `urlTextBox` if the user is not typing in it.
1685 if (!urlTextBox.hasFocus()) {
1686 // Display the formatted URL text.
1687 urlTextBox.setText(formattedUrlString);
1689 // Apply text highlighting to `urlTextBox`.
1694 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1695 sslCertificate = mainWebView.getCertificate();
1697 // 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.
1698 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1699 // Initialize the current SSL certificate variables.
1700 String currentWebsiteIssuedToCName = "";
1701 String currentWebsiteIssuedToOName = "";
1702 String currentWebsiteIssuedToUName = "";
1703 String currentWebsiteIssuedByCName = "";
1704 String currentWebsiteIssuedByOName = "";
1705 String currentWebsiteIssuedByUName = "";
1706 Date currentWebsiteSslStartDate = null;
1707 Date currentWebsiteSslEndDate = null;
1710 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1711 if (sslCertificate != null) {
1712 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1713 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1714 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1715 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1716 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1717 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1718 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1719 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1722 // 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`.
1723 String currentWebsiteSslStartDateString = "";
1724 String currentWebsiteSslEndDateString = "";
1725 String pinnedDomainSslStartDateString = "";
1726 String pinnedDomainSslEndDateString = "";
1728 // Convert the `Dates` to `Strings` if they are not `null`.
1729 if (currentWebsiteSslStartDate != null) {
1730 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1733 if (currentWebsiteSslEndDate != null) {
1734 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1737 if (pinnedDomainSslStartDate != null) {
1738 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1741 if (pinnedDomainSslEndDate != null) {
1742 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1745 // Check to see if the pinned SSL certificate matches the current website certificate.
1746 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1747 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1748 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1749 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1750 // The pinned SSL certificate doesn't match the current domain certificate.
1751 //Display the pinned SSL certificate mismatch `AlertDialog`.
1752 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1753 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1759 // Handle SSL Certificate errors.
1761 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1762 // Get the current website SSL certificate.
1763 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1765 // Extract the individual pieces of information from the current website SSL certificate.
1766 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1767 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1768 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1769 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1770 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1771 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1772 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1773 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1775 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1776 if (pinnedDomainSslCertificate &&
1777 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1778 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1779 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1780 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1781 // An SSL certificate is pinned and matches the current domain certificate.
1782 // Proceed to the website without displaying an error.
1784 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1785 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1786 sslErrorHandler = handler;
1788 // Display the SSL error `AlertDialog`.
1789 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1790 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1795 // Load the website if not waiting for Orbot to connect.
1796 if (!waitingForOrbot) {
1797 loadUrl(formattedUrlString);
1802 protected void onNewIntent(Intent intent) {
1803 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1806 // Check to see if the intent contains a new URL.
1807 if (intent.getData() != null) {
1808 // Get the intent data.
1809 final Uri intentUriData = intent.getData();
1811 // Load the website.
1812 loadUrl(intentUriData.toString());
1814 // Close the navigation drawer if it is open.
1815 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1816 drawerLayout.closeDrawer(GravityCompat.START);
1819 // Close the bookmarks drawer if it is open.
1820 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1821 drawerLayout.closeDrawer(GravityCompat.END);
1824 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1825 mainWebView.requestFocus();
1830 public void onRestart() {
1831 // Run the default commands.
1834 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1835 if (proxyThroughOrbot) {
1836 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1837 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1839 // Send the intent to the Orbot package.
1840 orbotIntent.setPackage("org.torproject.android");
1843 sendBroadcast(orbotIntent);
1846 // Apply the app settings if returning from the Settings activity..
1847 if (reapplyAppSettingsOnRestart) {
1848 // Apply the app settings.
1851 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1852 if (reloadOnRestart) {
1853 // Reload `mainWebView`.
1854 mainWebView.reload();
1856 // Reset `reloadOnRestartBoolean`.
1857 reloadOnRestart = false;
1860 // Reset the return from settings flag.
1861 reapplyAppSettingsOnRestart = false;
1864 // Apply the domain settings if returning from the Domains activity.
1865 if (reapplyDomainSettingsOnRestart) {
1866 // Reapply the domain settings.
1867 applyDomainSettings(formattedUrlString, false, true);
1869 // Reset `reapplyDomainSettingsOnRestart`.
1870 reapplyDomainSettingsOnRestart = false;
1873 // Load the URL on restart to apply changes to night mode.
1874 if (loadUrlOnRestart) {
1875 // Load the current `formattedUrlString`.
1876 loadUrl(formattedUrlString);
1878 // Reset `loadUrlOnRestart.
1879 loadUrlOnRestart = false;
1882 // Update the bookmarks drawer if returning from the Bookmarks activity.
1883 if (restartFromBookmarksActivity) {
1884 // Close the bookmarks drawer.
1885 drawerLayout.closeDrawer(GravityCompat.END);
1887 // Reload the bookmarks drawer.
1888 loadBookmarksFolder();
1890 // Reset `restartFromBookmarksActivity`.
1891 restartFromBookmarksActivity = false;
1894 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1895 updatePrivacyIcons(true);
1898 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1900 public void onResume() {
1901 // Run the default commands.
1904 // Resume JavaScript (if enabled).
1905 mainWebView.resumeTimers();
1907 // Resume `mainWebView`.
1908 mainWebView.onResume();
1910 // Resume the adView for the free flavor.
1911 if (BuildConfig.FLAVOR.contentEquals("free")) {
1913 AdHelper.resumeAd(findViewById(R.id.adview));
1916 // Display a message to the user if waiting for Orbot.
1917 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1918 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
1919 mainWebView.getSettings().setUseWideViewPort(false);
1921 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1922 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1925 if (displayingFullScreenVideo) {
1926 // Remove the translucent overlays.
1927 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1929 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1930 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1932 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1933 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1934 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1936 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1941 public void onPause() {
1942 // Run the default commands.
1945 // Pause `mainWebView`.
1946 mainWebView.onPause();
1948 // Stop all JavaScript.
1949 mainWebView.pauseTimers();
1951 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1952 if (BuildConfig.FLAVOR.contentEquals("free")) {
1954 AdHelper.pauseAd(findViewById(R.id.adview));
1959 public void onDestroy() {
1960 // Unregister the Orbot status broadcast receiver.
1961 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1963 // Run the default commands.
1968 public boolean onCreateOptionsMenu(Menu menu) {
1969 // Inflate the menu; this adds items to the action bar if it is present.
1970 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1972 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1975 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1976 updatePrivacyIcons(false);
1978 // Get handles for the menu items.
1979 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1980 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1981 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1982 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1983 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1984 refreshMenuItem = menu.findItem(R.id.refresh);
1985 blocklistsMenuItem = menu.findItem(R.id.blocklists);
1986 easyListMenuItem = menu.findItem(R.id.easylist);
1987 easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1988 fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1989 fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1990 ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1991 blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1992 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1994 // Only display third-party cookies if API >= 21
1995 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1997 // Only display the form data menu items if the API < 26.
1998 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1999 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
2001 // Only show Ad Consent if this is the free flavor.
2002 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
2004 // Get the shared preference values.
2005 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2007 // Get the status of the additional AppBar icons.
2008 displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
2010 // 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.
2011 if (displayAdditionalAppBarIcons) {
2012 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2013 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2014 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
2015 } else { //Do not display the additional icons.
2016 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2017 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2018 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2021 // Replace Refresh with Stop if a URL is already loading.
2024 refreshMenuItem.setTitle(R.string.stop);
2026 // If the icon is displayed in the AppBar, set it according to the theme.
2027 if (displayAdditionalAppBarIcons) {
2029 refreshMenuItem.setIcon(R.drawable.close_dark);
2031 refreshMenuItem.setIcon(R.drawable.close_light);
2040 public boolean onPrepareOptionsMenu(Menu menu) {
2041 // Get handles for the menu items.
2042 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2043 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2044 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2045 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2046 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
2047 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2048 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2049 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2050 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
2051 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2052 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
2053 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2054 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
2056 // Set the text for the domain menu item.
2057 if (domainSettingsApplied) {
2058 addOrEditDomain.setTitle(R.string.edit_domain_settings);
2060 addOrEditDomain.setTitle(R.string.add_domain_settings);
2063 // Set the status of the menu item checkboxes.
2064 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2065 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2066 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2067 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
2068 easyListMenuItem.setChecked(easyListEnabled);
2069 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
2070 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
2071 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
2072 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
2073 blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
2074 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
2075 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2076 nightModeMenuItem.setChecked(nightMode);
2078 // Enable third-party cookies if first-party cookies are enabled.
2079 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2081 // Enable DOM Storage if JavaScript is enabled.
2082 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2084 // Enable Clear Cookies if there are any.
2085 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2087 // Get a count of the number of files in the Local Storage directory.
2088 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2089 int localStorageDirectoryNumberOfFiles = 0;
2090 if (localStorageDirectory.exists()) {
2091 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2094 // Get a count of the number of files in the IndexedDB directory.
2095 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2096 int indexedDBDirectoryNumberOfFiles = 0;
2097 if (indexedDBDirectory.exists()) {
2098 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2101 // Enable Clear DOM Storage if there is any.
2102 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2104 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
2105 if (Build.VERSION.SDK_INT < 26) {
2106 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2107 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2109 // Disable clear form data because it is not supported on current version of Android.
2110 clearFormDataMenuItem.setEnabled(false);
2113 // Enable Clear Data if any of the submenu items are enabled.
2114 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2116 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2117 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2119 // Initialize the display names for the blocklists with the number of blocked requests.
2120 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
2121 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2122 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2123 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2124 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2125 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2126 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2128 // Get the current user agent.
2129 String currentUserAgent = mainWebView.getSettings().getUserAgentString();
2131 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
2132 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
2133 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
2134 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
2135 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
2136 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
2137 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
2138 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
2139 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
2140 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
2141 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
2142 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
2143 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
2144 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
2145 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
2146 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
2147 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
2148 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
2149 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
2150 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
2151 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
2152 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
2153 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
2154 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
2155 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
2156 } else { // Custom user agent.
2157 menu.findItem(R.id.user_agent_custom).setChecked(true);
2160 // Initialize font size variables.
2161 int fontSize = mainWebView.getSettings().getTextZoom();
2162 String fontSizeTitle;
2163 MenuItem selectedFontSizeMenuItem;
2165 // Prepare the font size title and current size menu item.
2168 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2169 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2173 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2174 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2178 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2179 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2183 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2184 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2188 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2189 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2193 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2194 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2198 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2199 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2203 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2204 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2208 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2209 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2213 // Set the font size title and select the current size menu item.
2214 fontSizeMenuItem.setTitle(fontSizeTitle);
2215 selectedFontSizeMenuItem.setChecked(true);
2217 // Run all the other default commands.
2218 super.onPrepareOptionsMenu(menu);
2220 // Display the menu.
2225 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2226 @SuppressLint("SetJavaScriptEnabled")
2227 // removeAllCookies is deprecated, but it is required for API < 21.
2228 @SuppressWarnings("deprecation")
2229 public boolean onOptionsItemSelected(MenuItem menuItem) {
2230 // Get the selected menu item ID.
2231 int menuItemId = menuItem.getItemId();
2233 // Set the commands that relate to the menu entries.
2234 switch (menuItemId) {
2235 case R.id.toggle_javascript:
2236 // Switch the status of javaScriptEnabled.
2237 javaScriptEnabled = !javaScriptEnabled;
2239 // Apply the new JavaScript status.
2240 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2242 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2243 updatePrivacyIcons(true);
2245 // Display a `Snackbar`.
2246 if (javaScriptEnabled) { // JavaScrip is enabled.
2247 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2248 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2249 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2250 } else { // Privacy mode.
2251 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2254 // Reload the WebView.
2255 mainWebView.reload();
2258 case R.id.add_or_edit_domain:
2259 if (domainSettingsApplied) { // Edit the current domain settings.
2260 // Reapply the domain settings on returning to `MainWebViewActivity`.
2261 reapplyDomainSettingsOnRestart = true;
2262 currentDomainName = "";
2264 // Create an intent to launch the domains activity.
2265 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2267 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2268 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2269 domainsIntent.putExtra("closeOnBack", true);
2272 startActivity(domainsIntent);
2273 } else { // Add a new domain.
2274 // Apply the new domain settings on returning to `MainWebViewActivity`.
2275 reapplyDomainSettingsOnRestart = true;
2276 currentDomainName = "";
2278 // Get the current domain
2279 Uri currentUri = Uri.parse(formattedUrlString);
2280 String currentDomain = currentUri.getHost();
2282 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2283 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2285 // Create the domain and store the database ID.
2286 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2288 // Create an intent to launch the domains activity.
2289 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2291 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2292 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2293 domainsIntent.putExtra("closeOnBack", true);
2296 startActivity(domainsIntent);
2300 case R.id.toggle_first_party_cookies:
2301 // Switch the status of firstPartyCookiesEnabled.
2302 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2304 // Update the menu checkbox.
2305 menuItem.setChecked(firstPartyCookiesEnabled);
2307 // Apply the new cookie status.
2308 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2310 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2311 updatePrivacyIcons(true);
2313 // Display a `Snackbar`.
2314 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2315 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2316 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2317 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2318 } else { // Privacy mode.
2319 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2322 // Reload the WebView.
2323 mainWebView.reload();
2326 case R.id.toggle_third_party_cookies:
2327 if (Build.VERSION.SDK_INT >= 21) {
2328 // Switch the status of thirdPartyCookiesEnabled.
2329 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2331 // Update the menu checkbox.
2332 menuItem.setChecked(thirdPartyCookiesEnabled);
2334 // Apply the new cookie status.
2335 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2337 // Display a `Snackbar`.
2338 if (thirdPartyCookiesEnabled) {
2339 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2341 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2344 // Reload the WebView.
2345 mainWebView.reload();
2346 } // Else do nothing because SDK < 21.
2349 case R.id.toggle_dom_storage:
2350 // Switch the status of domStorageEnabled.
2351 domStorageEnabled = !domStorageEnabled;
2353 // Update the menu checkbox.
2354 menuItem.setChecked(domStorageEnabled);
2356 // Apply the new DOM Storage status.
2357 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2359 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2360 updatePrivacyIcons(true);
2362 // Display a `Snackbar`.
2363 if (domStorageEnabled) {
2364 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2366 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2369 // Reload the WebView.
2370 mainWebView.reload();
2373 // Form data can be removed once the minimum API >= 26.
2374 case R.id.toggle_save_form_data:
2375 // Switch the status of saveFormDataEnabled.
2376 saveFormDataEnabled = !saveFormDataEnabled;
2378 // Update the menu checkbox.
2379 menuItem.setChecked(saveFormDataEnabled);
2381 // Apply the new form data status.
2382 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2384 // Display a `Snackbar`.
2385 if (saveFormDataEnabled) {
2386 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2388 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2391 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2392 updatePrivacyIcons(true);
2394 // Reload the WebView.
2395 mainWebView.reload();
2398 case R.id.clear_cookies:
2399 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2400 .setAction(R.string.undo, v -> {
2401 // Do nothing because everything will be handled by `onDismissed()` below.
2403 .addCallback(new Snackbar.Callback() {
2405 public void onDismissed(Snackbar snackbar, int event) {
2407 // The user pushed the `Undo` button.
2408 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2412 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2414 // `cookieManager.removeAllCookie()` varies by SDK.
2415 if (Build.VERSION.SDK_INT < 21) {
2416 cookieManager.removeAllCookie();
2418 // `null` indicates no callback.
2419 cookieManager.removeAllCookies(null);
2427 case R.id.clear_dom_storage:
2428 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2429 .setAction(R.string.undo, v -> {
2430 // Do nothing because everything will be handled by `onDismissed()` below.
2432 .addCallback(new Snackbar.Callback() {
2434 public void onDismissed(Snackbar snackbar, int event) {
2436 // The user pushed the `Undo` button.
2437 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2441 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2443 // Delete the DOM Storage.
2444 WebStorage webStorage = WebStorage.getInstance();
2445 webStorage.deleteAllData();
2447 // Manually delete the DOM storage files and directories.
2449 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2450 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2452 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2453 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2454 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2455 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2456 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2457 } catch (IOException e) {
2458 // Do nothing if an error is thrown.
2466 // Form data can be remove once the minimum API >= 26.
2467 case R.id.clear_form_data:
2468 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2469 .setAction(R.string.undo, v -> {
2470 // Do nothing because everything will be handled by `onDismissed()` below.
2472 .addCallback(new Snackbar.Callback() {
2474 public void onDismissed(Snackbar snackbar, int event) {
2476 // The user pushed the `Undo` button.
2477 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2481 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2483 // Delete the form data.
2484 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2485 mainWebViewDatabase.clearFormData();
2493 // Toggle the EasyList status.
2494 easyListEnabled = !easyListEnabled;
2496 // Update the menu checkbox.
2497 menuItem.setChecked(easyListEnabled);
2499 // Reload the main WebView.
2500 mainWebView.reload();
2503 case R.id.easyprivacy:
2504 // Toggle the EasyPrivacy status.
2505 easyPrivacyEnabled = !easyPrivacyEnabled;
2507 // Update the menu checkbox.
2508 menuItem.setChecked(easyPrivacyEnabled);
2510 // Reload the main WebView.
2511 mainWebView.reload();
2514 case R.id.fanboys_annoyance_list:
2515 // Toggle Fanboy's Annoyance List status.
2516 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2518 // Update the menu checkbox.
2519 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2521 // Update the staus of Fanboy's Social Blocking List.
2522 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2523 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2525 // Reload the main WebView.
2526 mainWebView.reload();
2529 case R.id.fanboys_social_blocking_list:
2530 // Toggle Fanboy's Social Blocking List status.
2531 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2533 // Update the menu checkbox.
2534 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2536 // Reload the main WebView.
2537 mainWebView.reload();
2540 case R.id.ultraprivacy:
2541 // Toggle the UltraPrivacy status.
2542 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2544 // Update the menu checkbox.
2545 menuItem.setChecked(ultraPrivacyEnabled);
2547 // Reload the main WebView.
2548 mainWebView.reload();
2551 case R.id.block_all_third_party_requests:
2552 //Toggle the third-party requests blocker status.
2553 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2555 // Update the menu checkbox.
2556 menuItem.setChecked(blockAllThirdPartyRequests);
2558 // Reload the main WebView.
2559 mainWebView.reload();
2562 case R.id.user_agent_privacy_browser:
2563 // Update the user agent.
2564 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
2566 // Reload the WebView.
2567 mainWebView.reload();
2570 case R.id.user_agent_webview_default:
2571 // Update the user agent.
2572 mainWebView.getSettings().setUserAgentString("");
2574 // Reload the WebView.
2575 mainWebView.reload();
2578 case R.id.user_agent_firefox_on_android:
2579 // Update the user agent.
2580 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
2582 // Reload the WebView.
2583 mainWebView.reload();
2586 case R.id.user_agent_chrome_on_android:
2587 // Update the user agent.
2588 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
2590 // Reload the WebView.
2591 mainWebView.reload();
2594 case R.id.user_agent_safari_on_ios:
2595 // Update the user agent.
2596 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
2598 // Reload the WebView.
2599 mainWebView.reload();
2602 case R.id.user_agent_firefox_on_linux:
2603 // Update the user agent.
2604 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
2606 // Reload the WebView.
2607 mainWebView.reload();
2610 case R.id.user_agent_chromium_on_linux:
2611 // Update the user agent.
2612 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
2614 // Reload the WebView.
2615 mainWebView.reload();
2618 case R.id.user_agent_firefox_on_windows:
2619 // Update the user agent.
2620 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
2622 // Reload the WebView.
2623 mainWebView.reload();
2626 case R.id.user_agent_chrome_on_windows:
2627 // Update the user agent.
2628 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
2630 // Reload the WebView.
2631 mainWebView.reload();
2634 case R.id.user_agent_edge_on_windows:
2635 // Update the user agent.
2636 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
2638 // Reload the WebView.
2639 mainWebView.reload();
2642 case R.id.user_agent_internet_explorer_on_windows:
2643 // Update the user agent.
2644 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
2646 // Reload the WebView.
2647 mainWebView.reload();
2650 case R.id.user_agent_safari_on_macos:
2651 // Update the user agent.
2652 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
2654 // Reload the WebView.
2655 mainWebView.reload();
2658 case R.id.user_agent_custom:
2659 // Update the user agent.
2660 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2662 // Reload the WebView.
2663 mainWebView.reload();
2666 case R.id.font_size_twenty_five_percent:
2667 mainWebView.getSettings().setTextZoom(25);
2670 case R.id.font_size_fifty_percent:
2671 mainWebView.getSettings().setTextZoom(50);
2674 case R.id.font_size_seventy_five_percent:
2675 mainWebView.getSettings().setTextZoom(75);
2678 case R.id.font_size_one_hundred_percent:
2679 mainWebView.getSettings().setTextZoom(100);
2682 case R.id.font_size_one_hundred_twenty_five_percent:
2683 mainWebView.getSettings().setTextZoom(125);
2686 case R.id.font_size_one_hundred_fifty_percent:
2687 mainWebView.getSettings().setTextZoom(150);
2690 case R.id.font_size_one_hundred_seventy_five_percent:
2691 mainWebView.getSettings().setTextZoom(175);
2694 case R.id.font_size_two_hundred_percent:
2695 mainWebView.getSettings().setTextZoom(200);
2698 case R.id.swipe_to_refresh:
2699 // Toggle swipe to refresh.
2700 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2703 case R.id.display_images:
2704 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2705 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2706 mainWebView.reload();
2707 } else { // Images are not currently loaded automatically.
2708 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2711 // Set `onTheFlyDisplayImagesSet`.
2712 onTheFlyDisplayImagesSet = true;
2715 case R.id.night_mode:
2716 // Toggle night mode.
2717 nightMode = !nightMode;
2719 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
2720 if (nightMode) { // Night mode is enabled. Enable JavaScript.
2721 // Update the global variable.
2722 javaScriptEnabled = true;
2723 } else if (domainSettingsApplied) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
2724 // Get the JavaScript preference that was stored the last time domain settings were loaded.
2725 javaScriptEnabled = domainSettingsJavaScriptEnabled;
2726 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
2727 // Get a handle for the shared preference.
2728 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2730 // Get the JavaScript preference.
2731 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2734 // Apply the JavaScript setting to the WebView.
2735 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2737 // Update the privacy icons.
2738 updatePrivacyIcons(false);
2740 // Reload the website.
2741 mainWebView.reload();
2744 case R.id.view_source:
2745 // Launch the View Source activity.
2746 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2747 startActivity(viewSourceIntent);
2751 // Setup the share string.
2752 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2754 // Create the share intent.
2755 Intent shareIntent = new Intent();
2756 shareIntent.setAction(Intent.ACTION_SEND);
2757 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2758 shareIntent.setType("text/plain");
2761 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2764 case R.id.find_on_page:
2765 // Hide the URL app bar.
2766 supportAppBar.setVisibility(View.GONE);
2768 // Show the Find on Page `RelativeLayout`.
2769 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2771 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2772 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2773 findOnPageEditText.postDelayed(() -> {
2774 // Set the focus on `findOnPageEditText`.
2775 findOnPageEditText.requestFocus();
2777 // Display the keyboard. `0` sets no input flags.
2778 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2783 // Get a `PrintManager` instance.
2784 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2786 // Convert `mainWebView` to `printDocumentAdapter`.
2787 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2789 // Remove the lint error below that `printManager` might be `null`.
2790 assert printManager != null;
2792 // Print the document. The print attributes are `null`.
2793 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2796 case R.id.add_to_homescreen:
2797 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2798 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2799 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2801 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2805 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2806 // Reload the WebView.
2807 mainWebView.reload();
2808 } else { // The stop button was pushed.
2809 // Stop the loading of the WebView.
2810 mainWebView.stopLoading();
2814 case R.id.ad_consent:
2815 // Display the ad consent dialog.
2816 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2817 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2821 // Don't consume the event.
2822 return super.onOptionsItemSelected(menuItem);
2826 // removeAllCookies is deprecated, but it is required for API < 21.
2827 @SuppressWarnings("deprecation")
2829 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2830 int menuItemId = menuItem.getItemId();
2832 switch (menuItemId) {
2838 if (mainWebView.canGoBack()) {
2839 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2840 formattedUrlString = "";
2842 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2843 navigatingHistory = true;
2845 // Load the previous website in the history.
2846 mainWebView.goBack();
2851 if (mainWebView.canGoForward()) {
2852 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2853 formattedUrlString = "";
2855 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2856 navigatingHistory = true;
2858 // Load the next website in the history.
2859 mainWebView.goForward();
2864 // Get the `WebBackForwardList`.
2865 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2867 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2868 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2869 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2873 // Launch the requests activity.
2874 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2875 startActivity(requestsIntent);
2878 case R.id.downloads:
2879 // Launch the system Download Manager.
2880 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2882 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2883 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2885 startActivity(downloadManagerIntent);
2889 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2890 reapplyDomainSettingsOnRestart = true;
2891 currentDomainName = "";
2893 // Launch the domains activity.
2894 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2895 startActivity(domainsIntent);
2899 // Set the flag to reapply app settings on restart when returning from Settings.
2900 reapplyAppSettingsOnRestart = true;
2902 // Set the flag to reapply the domain settings on restart when returning from Settings.
2903 reapplyDomainSettingsOnRestart = true;
2904 currentDomainName = "";
2906 // Launch the settings activity.
2907 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2908 startActivity(settingsIntent);
2912 // Launch `GuideActivity`.
2913 Intent guideIntent = new Intent(this, GuideActivity.class);
2914 startActivity(guideIntent);
2918 // Launch `AboutActivity`.
2919 Intent aboutIntent = new Intent(this, AboutActivity.class);
2920 startActivity(aboutIntent);
2923 case R.id.clearAndExit:
2924 // Get a handle for `sharedPreferences`. `this` references the current context.
2925 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2927 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2930 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2931 // The command to remove cookies changed slightly in API 21.
2932 if (Build.VERSION.SDK_INT >= 21) {
2933 cookieManager.removeAllCookies(null);
2935 cookieManager.removeAllCookie();
2938 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2940 // We have to use two commands because `Runtime.exec()` does not like `*`.
2941 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2942 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2943 } catch (IOException e) {
2944 // Do nothing if an error is thrown.
2948 // Clear DOM storage.
2949 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2950 // Ask `WebStorage` to clear the DOM storage.
2951 WebStorage webStorage = WebStorage.getInstance();
2952 webStorage.deleteAllData();
2954 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2956 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2957 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2959 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2960 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2961 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2962 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2963 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2964 } catch (IOException e) {
2965 // Do nothing if an error is thrown.
2969 // Clear form data if the API < 26.
2970 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2971 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2972 webViewDatabase.clearFormData();
2974 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2976 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2977 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2978 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2979 } catch (IOException e) {
2980 // Do nothing if an error is thrown.
2985 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2986 // `true` includes disk files.
2987 mainWebView.clearCache(true);
2989 // Manually delete the cache directories.
2991 // Delete the main cache directory.
2992 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2994 // Delete the secondary `Service Worker` cache directory.
2995 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2996 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2997 } catch (IOException e) {
2998 // Do nothing if an error is thrown.
3002 // Clear SSL certificate preferences.
3003 mainWebView.clearSslPreferences();
3005 // Clear the back/forward history.
3006 mainWebView.clearHistory();
3008 // Clear `formattedUrlString`.
3009 formattedUrlString = null;
3011 // Clear `customHeaders`.
3012 customHeaders.clear();
3014 // Detach all views from `mainWebViewRelativeLayout`.
3015 mainWebViewRelativeLayout.removeAllViews();
3017 // Destroy the internal state of `mainWebView`.
3018 mainWebView.destroy();
3020 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
3021 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
3022 if (clearEverything) {
3024 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
3025 } catch (IOException e) {
3026 // Do nothing if an error is thrown.
3030 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
3031 if (Build.VERSION.SDK_INT >= 21) {
3032 finishAndRemoveTask();
3037 // Remove the terminated program from RAM. The status code is `0`.
3042 // Close the navigation drawer.
3043 drawerLayout.closeDrawer(GravityCompat.START);
3048 public void onPostCreate(Bundle savedInstanceState) {
3049 super.onPostCreate(savedInstanceState);
3051 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
3052 drawerToggle.syncState();
3056 public void onConfigurationChanged(Configuration newConfig) {
3057 super.onConfigurationChanged(newConfig);
3059 // Reload the ad for the free flavor if we not in full screen mode.
3060 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
3061 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3062 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
3065 // `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:
3066 // https://code.google.com/p/android/issues/detail?id=20493#c8
3067 // ActivityCompat.invalidateOptionsMenu(this);
3071 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
3072 // Store the `HitTestResult`.
3073 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
3076 final String imageUrl;
3077 final String linkUrl;
3079 // Get a handle for the `ClipboardManager`.
3080 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
3082 // Remove the lint errors below that `clipboardManager` might be `null`.
3083 assert clipboardManager != null;
3085 switch (hitTestResult.getType()) {
3086 // `SRC_ANCHOR_TYPE` is a link.
3087 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
3088 // Get the target URL.
3089 linkUrl = hitTestResult.getExtra();
3091 // Set the target URL as the title of the `ContextMenu`.
3092 menu.setHeaderTitle(linkUrl);
3094 // Add a Load URL entry.
3095 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
3100 // Add a Copy URL entry.
3101 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
3102 // Save the link URL in a `ClipData`.
3103 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
3105 // Set the `ClipData` as the clipboard's primary clip.
3106 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
3110 // Add a Download URL entry.
3111 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
3112 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3113 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3114 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3116 // Store the variables for future use by `onRequestPermissionsResult()`.
3117 downloadUrl = linkUrl;
3118 downloadContentDisposition = "none";
3119 downloadContentLength = -1;
3121 // Show a dialog if the user has previously denied the permission.
3122 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3123 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
3124 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
3126 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
3127 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3128 } else { // Show the permission request directly.
3129 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
3130 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3132 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3133 // Get a handle for the download file alert dialog.
3134 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
3136 // Show the download file alert dialog.
3137 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3142 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3143 menu.add(R.string.cancel);
3146 case WebView.HitTestResult.EMAIL_TYPE:
3147 // Get the target URL.
3148 linkUrl = hitTestResult.getExtra();
3150 // Set the target URL as the title of the `ContextMenu`.
3151 menu.setHeaderTitle(linkUrl);
3153 // Add a `Write Email` entry.
3154 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
3155 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
3156 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
3158 // Parse the url and set it as the data for the `Intent`.
3159 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
3161 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
3162 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3165 startActivity(emailIntent);
3169 // Add a `Copy Email Address` entry.
3170 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
3171 // Save the email address in a `ClipData`.
3172 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
3174 // Set the `ClipData` as the clipboard's primary clip.
3175 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
3179 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3180 menu.add(R.string.cancel);
3183 // `IMAGE_TYPE` is an image.
3184 case WebView.HitTestResult.IMAGE_TYPE:
3185 // Get the image URL.
3186 imageUrl = hitTestResult.getExtra();
3188 // Set the image URL as the title of the `ContextMenu`.
3189 menu.setHeaderTitle(imageUrl);
3191 // Add a `View Image` entry.
3192 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3197 // Add a `Download Image` entry.
3198 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3199 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3200 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3201 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3203 // Store the image URL for use by `onRequestPermissionResult()`.
3204 downloadImageUrl = imageUrl;
3206 // Show a dialog if the user has previously denied the permission.
3207 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3208 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3209 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3211 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3212 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3213 } else { // Show the permission request directly.
3214 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3215 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3217 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3218 // Get a handle for the download image alert dialog.
3219 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3221 // Show the download image alert dialog.
3222 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3227 // Add a `Copy URL` entry.
3228 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3229 // Save the image URL in a `ClipData`.
3230 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3232 // Set the `ClipData` as the clipboard's primary clip.
3233 clipboardManager.setPrimaryClip(srcImageTypeClipData);
3237 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3238 menu.add(R.string.cancel);
3242 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
3243 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
3244 // Get the image URL.
3245 imageUrl = hitTestResult.getExtra();
3247 // Set the image URL as the title of the `ContextMenu`.
3248 menu.setHeaderTitle(imageUrl);
3250 // Add a `View Image` entry.
3251 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3256 // Add a `Download Image` entry.
3257 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3258 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3259 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3260 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3262 // Store the image URL for use by `onRequestPermissionResult()`.
3263 downloadImageUrl = imageUrl;
3265 // Show a dialog if the user has previously denied the permission.
3266 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3267 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3268 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3270 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3271 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3272 } else { // Show the permission request directly.
3273 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3274 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3276 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3277 // Get a handle for the download image alert dialog.
3278 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3280 // Show the download image alert dialog.
3281 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3286 // Add a `Copy URL` entry.
3287 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3288 // Save the image URL in a `ClipData`.
3289 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3291 // Set the `ClipData` as the clipboard's primary clip.
3292 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3296 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3297 menu.add(R.string.cancel);
3303 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3304 // Get the `EditTexts` from the `dialogFragment`.
3305 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3306 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3308 // Extract the strings from the `EditTexts`.
3309 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3310 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3312 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3313 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3314 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3315 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3317 // Display the new bookmark below the current items in the (0 indexed) list.
3318 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3320 // Create the bookmark.
3321 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3323 // Update `bookmarksCursor` with the current contents of this folder.
3324 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3326 // Update the `ListView`.
3327 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3329 // Scroll to the new bookmark.
3330 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3334 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3335 // Get handles for the views in `dialogFragment`.
3336 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3337 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3338 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3340 // Get new folder name string.
3341 String folderNameString = createFolderNameEditText.getText().toString();
3343 // Get the new folder icon `Bitmap`.
3344 Bitmap folderIconBitmap;
3345 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3346 // Get the default folder icon and convert it to a `Bitmap`.
3347 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3348 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3349 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3350 } else { // Use the `WebView` favorite icon.
3351 folderIconBitmap = favoriteIconBitmap;
3354 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3355 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3356 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3357 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3359 // Move all the bookmarks down one in the display order.
3360 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3361 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3362 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3365 // Create the folder, which will be placed at the top of the `ListView`.
3366 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3368 // Update `bookmarksCursor` with the current contents of this folder.
3369 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3371 // Update the `ListView`.
3372 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3374 // Scroll to the new folder.
3375 bookmarksListView.setSelection(0);
3379 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3380 // Get the shortcut name.
3381 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3382 String shortcutNameString = shortcutNameEditText.getText().toString();
3384 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3385 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3387 // Setup the shortcut intent.
3388 Intent shortcutIntent = new Intent();
3389 shortcutIntent.setAction(Intent.ACTION_VIEW);
3390 shortcutIntent.setData(Uri.parse(formattedUrlString));
3392 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3393 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3395 // Add the required fields to the shortcut info builder.
3396 shortcutInfoBuilder.setIcon(favoriteIcon);
3397 shortcutInfoBuilder.setIntent(shortcutIntent);
3398 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3400 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3401 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3405 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3406 switch (downloadType) {
3407 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3408 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3409 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3412 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3413 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3414 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3420 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
3421 switch (requestCode) {
3422 case DOWNLOAD_FILE_REQUEST_CODE:
3423 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3424 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3426 // On API 23, displaying the fragment must be delayed or the app will crash.
3427 if (Build.VERSION.SDK_INT == 23) {
3428 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3430 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3433 // Reset the download variables.
3435 downloadContentDisposition = "";
3436 downloadContentLength = 0;
3439 case DOWNLOAD_IMAGE_REQUEST_CODE:
3440 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3441 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3443 // On API 23, displaying the fragment must be delayed or the app will crash.
3444 if (Build.VERSION.SDK_INT == 23) {
3445 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3447 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3450 // Reset the image URL variable.
3451 downloadImageUrl = "";
3457 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3458 // Download the image if it has an HTTP or HTTPS URI.
3459 if (imageUrl.startsWith("http")) {
3460 // Get a handle for the system `DOWNLOAD_SERVICE`.
3461 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3463 // Parse `imageUrl`.
3464 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3466 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3467 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3468 if (firstPartyCookiesEnabled) {
3469 // Get the cookies for `imageUrl`.
3470 String cookies = cookieManager.getCookie(imageUrl);
3472 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3473 downloadRequest.addRequestHeader("Cookie", cookies);
3476 // Get the file name from the dialog fragment.
3477 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3478 String imageName = downloadImageNameEditText.getText().toString();
3480 // Specify the download location.
3481 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3482 // Download to the public download directory.
3483 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3484 } else { // External write permission denied.
3485 // Download to the app's external download directory.
3486 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3489 // Allow `MediaScanner` to index the download if it is a media file.
3490 downloadRequest.allowScanningByMediaScanner();
3492 // Add the URL as the description for the download.
3493 downloadRequest.setDescription(imageUrl);
3495 // Show the download notification after the download is completed.
3496 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3498 // Remove the lint warning below that `downloadManager` might be `null`.
3499 assert downloadManager != null;
3501 // Initiate the download.
3502 downloadManager.enqueue(downloadRequest);
3503 } else { // The image is not an HTTP or HTTPS URI.
3504 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3509 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3510 // Download the file if it has an HTTP or HTTPS URI.
3511 if (downloadUrl.startsWith("http")) {
3512 // Get a handle for the system `DOWNLOAD_SERVICE`.
3513 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3515 // Parse `downloadUrl`.
3516 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3518 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3519 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3520 if (firstPartyCookiesEnabled) {
3521 // Get the cookies for `downloadUrl`.
3522 String cookies = cookieManager.getCookie(downloadUrl);
3524 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3525 downloadRequest.addRequestHeader("Cookie", cookies);
3528 // Get the file name from the dialog fragment.
3529 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3530 String fileName = downloadFileNameEditText.getText().toString();
3532 // Specify the download location.
3533 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3534 // Download to the public download directory.
3535 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3536 } else { // External write permission denied.
3537 // Download to the app's external download directory.
3538 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3541 // Allow `MediaScanner` to index the download if it is a media file.
3542 downloadRequest.allowScanningByMediaScanner();
3544 // Add the URL as the description for the download.
3545 downloadRequest.setDescription(downloadUrl);
3547 // Show the download notification after the download is completed.
3548 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3550 // Remove the lint warning below that `downloadManager` might be `null`.
3551 assert downloadManager != null;
3553 // Initiate the download.
3554 downloadManager.enqueue(downloadRequest);
3555 } else { // The download is not an HTTP or HTTPS URI.
3556 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3561 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3562 // Get handles for the views from `dialogFragment`.
3563 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3564 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3565 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3567 // Store the bookmark strings.
3568 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3569 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3571 // Update the bookmark.
3572 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3573 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3574 } else { // Update the bookmark using the `WebView` favorite icon.
3575 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3576 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3577 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3578 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3580 // Update the bookmark and the favorite icon.
3581 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3584 // Update `bookmarksCursor` with the current contents of this folder.
3585 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3587 // Update the `ListView`.
3588 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3592 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3593 // Get handles for the views from `dialogFragment`.
3594 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3595 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3596 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3597 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3599 // Get the new folder name.
3600 String newFolderNameString = editFolderNameEditText.getText().toString();
3602 // Check if the favorite icon has changed.
3603 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3604 // Update the name in the database.
3605 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3606 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3607 // Get the new folder icon `Bitmap`.
3608 Bitmap folderIconBitmap;
3609 if (defaultFolderIconRadioButton.isChecked()) {
3610 // Get the default folder icon and convert it to a `Bitmap`.
3611 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3612 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3613 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3614 } else { // Use the `WebView` favorite icon.
3615 folderIconBitmap = favoriteIconBitmap;
3618 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3619 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3620 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3621 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3623 // Update the folder icon in the database.
3624 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3625 } else { // The folder icon and the name have changed.
3626 // Get the new folder icon `Bitmap`.
3627 Bitmap folderIconBitmap;
3628 if (defaultFolderIconRadioButton.isChecked()) {
3629 // Get the default folder icon and convert it to a `Bitmap`.
3630 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3631 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3632 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3633 } else { // Use the `WebView` favorite icon.
3634 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3637 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3638 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3639 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3640 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3642 // Update the folder name and icon in the database.
3643 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3646 // Update `bookmarksCursor` with the current contents of this folder.
3647 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3649 // Update the `ListView`.
3650 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3654 public void onHttpAuthenticationCancel() {
3655 // Cancel the `HttpAuthHandler`.
3656 httpAuthHandler.cancel();
3660 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3661 // Get handles for the `EditTexts`.
3662 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3663 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3665 // Proceed with the HTTP authentication.
3666 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3669 public void viewSslCertificate(View view) {
3670 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3671 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3672 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3676 public void onSslErrorCancel() {
3677 sslErrorHandler.cancel();
3681 public void onSslErrorProceed() {
3682 sslErrorHandler.proceed();
3686 public void onSslMismatchBack() {
3687 if (mainWebView.canGoBack()) { // There is a back page in the history.
3688 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3689 formattedUrlString = "";
3691 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3692 navigatingHistory = true;
3695 mainWebView.goBack();
3696 } else { // There are no pages to go back to.
3697 // Load a blank page
3703 public void onSslMismatchProceed() {
3704 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3705 ignorePinnedSslCertificate = true;
3709 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3710 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3711 formattedUrlString = "";
3713 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3714 navigatingHistory = true;
3716 // Load the history entry.
3717 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3721 public void onClearHistory() {
3722 // Clear the history.
3723 mainWebView.clearHistory();
3726 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3728 public void onBackPressed() {
3729 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3730 // Close the navigation drawer.
3731 drawerLayout.closeDrawer(GravityCompat.START);
3732 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3733 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3734 // close the bookmarks drawer.
3735 drawerLayout.closeDrawer(GravityCompat.END);
3736 } else { // A subfolder is displayed.
3737 // Place the former parent folder in `currentFolder`.
3738 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3740 // Load the new folder.
3741 loadBookmarksFolder();
3744 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3745 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3746 formattedUrlString = "";
3748 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3749 navigatingHistory = true;
3752 mainWebView.goBack();
3753 } else { // There isn't anything to do in Privacy Browser.
3754 // Pass `onBackPressed()` to the system.
3755 super.onBackPressed();
3759 // 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.
3761 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3762 // File uploads only work on API >= 21.
3763 if (Build.VERSION.SDK_INT >= 21) {
3764 // Pass the file to the WebView.
3765 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3769 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3770 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3771 String unformattedUrlString = urlTextBox.getText().toString().trim();
3773 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3774 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3775 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3776 if (!unformattedUrlString.startsWith("http")) {
3777 unformattedUrlString = "http://" + unformattedUrlString;
3780 // Initialize `unformattedUrl`.
3781 URL unformattedUrl = null;
3783 // 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.
3785 unformattedUrl = new URL(unformattedUrlString);
3786 } catch (MalformedURLException e) {
3787 e.printStackTrace();
3790 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3791 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3792 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3793 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3794 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3795 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3798 Uri.Builder formattedUri = new Uri.Builder();
3799 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3801 // Decode `formattedUri` as a `String` in `UTF-8`.
3802 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3803 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3804 // Load a blank string.
3805 formattedUrlString = "";
3806 } else { // Search for the contents of the URL box.
3807 // Sanitize the search input and convert it to a search.
3808 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3810 // Add the base search URL.
3811 formattedUrlString = searchURL + encodedUrlString;
3814 // 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.
3815 urlTextBox.clearFocus();
3818 loadUrl(formattedUrlString);
3821 private void loadUrl(String url) {// Apply any custom domain settings.
3822 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3823 formattedUrlString = url;
3825 // Apply the domain settings.
3826 applyDomainSettings(url, true, false);
3828 // If loading a website, set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3829 urlIsLoading = !url.equals("");
3832 mainWebView.loadUrl(url, customHeaders);
3835 public void findPreviousOnPage(View view) {
3836 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3837 mainWebView.findNext(false);
3840 public void findNextOnPage(View view) {
3841 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3842 mainWebView.findNext(true);
3845 public void closeFindOnPage(View view) {
3846 // Delete the contents of `find_on_page_edittext`.
3847 findOnPageEditText.setText(null);
3849 // Clear the highlighted phrases.
3850 mainWebView.clearMatches();
3852 // Hide the Find on Page `RelativeLayout`.
3853 findOnPageLinearLayout.setVisibility(View.GONE);
3855 // Show the URL app bar.
3856 supportAppBar.setVisibility(View.VISIBLE);
3858 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3859 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3862 private void applyAppSettings() {
3863 // Get a handle for the shared preferences.
3864 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3866 // Store the values from the shared preferences in variables.
3867 String homepageString = sharedPreferences.getString("homepage", "https://searx.me/");
3868 String torHomepageString = sharedPreferences.getString("tor_homepage", "http://ulrn6sryqaifefld.onion/");
3869 String torSearchString = sharedPreferences.getString("tor_search", "http://ulrn6sryqaifefld.onion/?q=");
3870 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3871 String searchString = sharedPreferences.getString("search", "https://searx.me/?q=");
3872 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3873 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3874 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3875 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3876 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3877 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3878 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3879 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3881 // Set the homepage, search, and proxy options.
3882 if (proxyThroughOrbot) { // Set the Tor options.
3883 // Set `torHomepageString` as `homepage`.
3884 homepage = torHomepageString;
3886 // If formattedUrlString is null assign the homepage to it.
3887 if (formattedUrlString == null) {
3888 formattedUrlString = homepage;
3891 // Set the search URL.
3892 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3893 searchURL = torSearchCustomURLString;
3894 } else { // Use the string from the pre-built list.
3895 searchURL = torSearchString;
3898 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3899 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3901 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3903 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3905 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3908 // Display a message to the user if waiting for Orbot.
3909 if (!orbotStatus.equals("ON")) {
3910 // Set `waitingForOrbot`.
3911 waitingForOrbot = true;
3913 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
3914 mainWebView.getSettings().setUseWideViewPort(false);
3916 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3917 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3919 } else { // Set the non-Tor options.
3920 // Set `homepageString` as `homepage`.
3921 homepage = homepageString;
3923 // If formattedUrlString is null assign the homepage to it.
3924 if (formattedUrlString == null) {
3925 formattedUrlString = homepage;
3928 // Set the search URL.
3929 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3930 searchURL = searchCustomURLString;
3931 } else { // Use the string from the pre-built list.
3932 searchURL = searchString;
3935 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3936 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3938 // Set the default `appBar` background. `this` refers to the context.
3940 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3942 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3945 // Reset `waitingForOrbot.
3946 waitingForOrbot = false;
3949 // Set Do Not Track status.
3950 if (doNotTrackEnabled) {
3951 customHeaders.put("DNT", "1");
3953 customHeaders.remove("DNT");
3956 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3957 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3958 if (hideSystemBarsOnFullscreen) { // Hide everything.
3959 // Remove the translucent navigation setting if it is currently flagged.
3960 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3962 // Remove the translucent status bar overlay.
3963 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3965 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3966 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3968 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3969 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3970 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3972 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3973 } else { // Hide everything except the status and navigation bars.
3974 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3975 rootCoordinatorLayout.setSystemUiVisibility(0);
3977 // Add the translucent status flag if it is unset.
3978 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3980 if (translucentNavigationBarOnFullscreen) {
3981 // Set the navigation bar to be translucent.
3982 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3984 // Set the navigation bar to be black.
3985 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3988 } else { // Privacy Browser is not in full screen browsing mode.
3989 // 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.
3990 inFullScreenBrowsingMode = false;
3992 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3993 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3997 // Show the `BannerAd` in the free flavor.
3998 if (BuildConfig.FLAVOR.contentEquals("free")) {
3999 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
4000 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
4003 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
4004 rootCoordinatorLayout.setSystemUiVisibility(0);
4006 // Remove the translucent navigation bar flag if it is set.
4007 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
4009 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
4010 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4012 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
4013 rootCoordinatorLayout.setFitsSystemWindows(true);
4017 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
4018 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
4019 @SuppressWarnings("deprecation")
4020 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
4021 // Parse the URL into a URI.
4022 Uri uri = Uri.parse(url);
4024 // Extract the domain from `uri`.
4025 String hostName = uri.getHost();
4027 // Initialize `loadingNewDomainName`.
4028 boolean loadingNewDomainName;
4030 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
4031 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
4032 //noinspection SimplifiableIfStatement
4033 if ((hostName == null) || (currentDomainName == null)) {
4034 loadingNewDomainName = true;
4035 } else { // Determine if `hostName` equals `currentDomainName`.
4036 loadingNewDomainName = !hostName.equals(currentDomainName);
4039 // Strings don't like to be null.
4040 if (hostName == null) {
4044 // 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.
4045 if (loadingNewDomainName) {
4046 // Set the new `hostname` as the `currentDomainName`.
4047 currentDomainName = hostName;
4049 // Reset `ignorePinnedSslCertificate`.
4050 ignorePinnedSslCertificate = false;
4052 // Reset the favorite icon if specified.
4053 if (resetFavoriteIcon) {
4054 favoriteIconBitmap = favoriteIconDefaultBitmap;
4055 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
4058 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
4059 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
4061 // Get a full cursor from `domainsDatabaseHelper`.
4062 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
4064 // Initialize `domainSettingsSet`.
4065 Set<String> domainSettingsSet = new HashSet<>();
4067 // Get the domain name column index.
4068 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
4070 // Populate `domainSettingsSet`.
4071 for (int i = 0; i < domainNameCursor.getCount(); i++) {
4072 // Move `domainsCursor` to the current row.
4073 domainNameCursor.moveToPosition(i);
4075 // Store the domain name in `domainSettingsSet`.
4076 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
4079 // Close `domainNameCursor.
4080 domainNameCursor.close();
4082 // Initialize variables to track if domain settings will be applied and, if so, under which name.
4083 domainSettingsApplied = false;
4084 String domainNameInDatabase = null;
4086 // Check the hostname.
4087 if (domainSettingsSet.contains(hostName)) {
4088 domainSettingsApplied = true;
4089 domainNameInDatabase = hostName;
4092 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
4093 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
4094 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
4095 // Apply the domain settings.
4096 domainSettingsApplied = true;
4098 // Store the applied domain names as it appears in the database.
4099 domainNameInDatabase = "*." + hostName;
4102 // Strip out the lowest subdomain of of the host name.
4103 hostName = hostName.substring(hostName.indexOf(".") + 1);
4107 // Get a handle for the shared preference.
4108 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4110 // Store the general preference information.
4111 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
4112 String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
4113 defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
4114 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
4115 nightMode = sharedPreferences.getBoolean("night_mode", false);
4117 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
4118 // Get a cursor for the current host and move it to the first position.
4119 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
4120 currentHostDomainSettingsCursor.moveToFirst();
4122 // Get the settings from the cursor.
4123 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
4124 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
4125 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
4126 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
4127 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
4128 // Form data can be removed once the minimum API >= 26.
4129 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
4130 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
4131 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
4132 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
4133 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
4134 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
4135 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
4136 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
4137 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
4138 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
4139 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
4140 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
4141 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
4142 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
4143 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
4144 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
4145 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
4146 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
4147 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
4149 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
4150 switch (nightModeInt) {
4151 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
4155 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
4160 // Store the domain JavaScript status. This is used by the options menu night mode toggle.
4161 domainSettingsJavaScriptEnabled = javaScriptEnabled;
4163 // Enable JavaScript if night mode is enabled.
4165 javaScriptEnabled = true;
4168 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
4169 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
4170 pinnedDomainSslStartDate = null;
4172 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
4175 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
4176 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
4177 pinnedDomainSslEndDate = null;
4179 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
4182 // Close `currentHostDomainSettingsCursor`.
4183 currentHostDomainSettingsCursor.close();
4185 // Apply the domain settings.
4186 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4187 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4188 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4190 // Apply the form data setting if the API < 26.
4191 if (Build.VERSION.SDK_INT < 26) {
4192 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4195 // Apply the font size.
4196 if (fontSize == 0) { // Apply the default font size.
4197 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4198 } else { // Apply the specified font size.
4199 mainWebView.getSettings().setTextZoom(fontSize);
4202 // Set third-party cookies status if API >= 21.
4203 if (Build.VERSION.SDK_INT >= 21) {
4204 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4207 // 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.
4208 // <https://redmine.stoutner.com/issues/160>
4209 if (!urlIsLoading) {
4210 // Set the user agent.
4211 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4212 // Get the array position of the default user agent name.
4213 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4215 // Set the user agent according to the system default.
4216 switch (defaultUserAgentArrayPosition) {
4217 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4218 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4219 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4222 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4223 // Set the user agent to `""`, which uses the default value.
4224 mainWebView.getSettings().setUserAgentString("");
4227 case SETTINGS_CUSTOM_USER_AGENT:
4228 // Set the custom user agent.
4229 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4233 // Get the user agent string from the user agent data array
4234 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4236 } else { // Set the user agent according to the stored name.
4237 // Get the array position of the user agent name.
4238 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4240 switch (userAgentArrayPosition) {
4241 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4242 mainWebView.getSettings().setUserAgentString(userAgentName);
4245 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4246 // Set the user agent to `""`, which uses the default value.
4247 mainWebView.getSettings().setUserAgentString("");
4251 // Get the user agent string from the user agent data array.
4252 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4256 // Set swipe to refresh.
4257 switch (swipeToRefreshInt) {
4258 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
4259 // Set swipe to refresh according to the default.
4260 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4263 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
4264 // Enable swipe to refresh.
4265 swipeRefreshLayout.setEnabled(true);
4268 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
4269 // Disable swipe to refresh.
4270 swipeRefreshLayout.setEnabled(false);
4273 // Store the applied user agent string, which is used in the View Source activity.
4274 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4277 // 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.
4279 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4281 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4283 } else { // The new URL does not have custom domain settings. Load the defaults.
4284 // Store the values from `sharedPreferences` in variables.
4285 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
4286 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
4287 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
4288 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
4289 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false); // Form data can be removed once the minimum API >= 26.
4290 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
4291 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
4292 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
4293 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
4294 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
4295 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
4297 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4299 javaScriptEnabled = true;
4302 // Apply the default settings.
4303 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4304 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4305 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4306 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4307 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4309 // Apply the form data setting if the API < 26.
4310 if (Build.VERSION.SDK_INT < 26) {
4311 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4314 // Reset the pinned SSL certificate information.
4315 domainSettingsDatabaseId = -1;
4316 pinnedDomainSslCertificate = false;
4317 pinnedDomainSslIssuedToCNameString = "";
4318 pinnedDomainSslIssuedToONameString = "";
4319 pinnedDomainSslIssuedToUNameString = "";
4320 pinnedDomainSslIssuedByCNameString = "";
4321 pinnedDomainSslIssuedByONameString = "";
4322 pinnedDomainSslIssuedByUNameString = "";
4323 pinnedDomainSslStartDate = null;
4324 pinnedDomainSslEndDate = null;
4326 // Set third-party cookies status if API >= 21.
4327 if (Build.VERSION.SDK_INT >= 21) {
4328 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4331 // 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.
4332 // <https://redmine.stoutner.com/issues/160>
4333 if (!urlIsLoading) {
4334 // Get the array position of the user agent name.
4335 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4337 // Set the user agent.
4338 switch (userAgentArrayPosition) {
4339 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4340 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4341 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4344 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4345 // Set the user agent to `""`, which uses the default value.
4346 mainWebView.getSettings().setUserAgentString("");
4349 case SETTINGS_CUSTOM_USER_AGENT:
4350 // Set the custom user agent.
4351 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4355 // Get the user agent string from the user agent data array
4356 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4359 // Store the applied user agent string, which is used in the View Source activity.
4360 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4363 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4364 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4367 // Close `domainsDatabaseHelper`.
4368 domainsDatabaseHelper.close();
4370 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
4371 onTheFlyDisplayImagesSet = false;
4372 setDisplayWebpageImages();
4374 // Update the privacy icons, but only if `mainMenu` has already been populated.
4375 if (mainMenu != null) {
4376 updatePrivacyIcons(true);
4380 // Reload the website if returning from the Domains activity.
4381 if (reloadWebsite) {
4382 mainWebView.reload();
4386 private void setDisplayWebpageImages() {
4387 if (!onTheFlyDisplayImagesSet) {
4388 if (domainSettingsApplied) { // Custom domain settings are applied.
4389 switch (displayWebpageImagesInt) {
4390 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4391 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4394 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4395 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4398 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4399 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4402 } else { // Default settings are applied.
4403 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4408 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4409 // Get handles for the menu items.
4410 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4411 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4412 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4413 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4415 // Update the privacy icon.
4416 if (javaScriptEnabled) { // JavaScript is enabled.
4417 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4418 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4419 privacyMenuItem.setIcon(R.drawable.warning);
4420 } else { // All the dangerous features are disabled.
4421 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4424 // Update the first-party cookies icon.
4425 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4426 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4427 } else { // First-party cookies are disabled.
4429 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4431 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4435 // Update the DOM storage icon.
4436 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4437 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4438 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4440 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4442 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4444 } else { // JavaScript is disabled, so DOM storage is ghosted.
4446 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4448 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4452 // Update the refresh icon.
4454 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4456 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4459 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4460 if (runInvalidateOptionsMenu) {
4461 invalidateOptionsMenu();
4465 private void highlightUrlText() {
4466 String urlString = urlTextBox.getText().toString();
4468 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4469 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4470 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4471 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4474 // Get the index of the `/` immediately after the domain name.
4475 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4477 // De-emphasize the text after the domain name.
4478 if (endOfDomainName > 0) {
4479 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4483 private void loadBookmarksFolder() {
4484 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4485 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4487 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4488 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4490 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4491 // Inflate the individual item layout. `false` does not attach it to the root.
4492 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4496 public void bindView(View view, Context context, Cursor cursor) {
4497 // Get handles for the views.
4498 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4499 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4501 // Get the favorite icon byte array from the cursor.
4502 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4504 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4505 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4507 // Display the bitmap in `bookmarkFavoriteIcon`.
4508 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4510 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4511 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4512 bookmarkNameTextView.setText(bookmarkNameString);
4514 // Make the font bold for folders.
4515 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4516 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4517 } else { // Reset the font to default for normal bookmarks.
4518 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4523 // Populate the `ListView` with the adapter.
4524 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4526 // Set the bookmarks drawer title.
4527 if (currentBookmarksFolder.isEmpty()) {
4528 bookmarksTitleTextView.setText(R.string.bookmarks);
4530 bookmarksTitleTextView.setText(currentBookmarksFolder);