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.DialogFragment;
27 import android.app.DownloadManager;
28 import android.content.ActivityNotFoundException;
29 import android.content.BroadcastReceiver;
30 import android.content.ClipData;
31 import android.content.ClipboardManager;
32 import android.content.Context;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.content.SharedPreferences;
36 import android.content.pm.PackageManager;
37 import android.content.res.Configuration;
38 import android.database.Cursor;
39 import android.graphics.Bitmap;
40 import android.graphics.BitmapFactory;
41 import android.graphics.Typeface;
42 import android.graphics.drawable.BitmapDrawable;
43 import android.graphics.drawable.Drawable;
44 import android.net.Uri;
45 import android.net.http.SslCertificate;
46 import android.net.http.SslError;
47 import android.os.Build;
48 import android.os.Bundle;
49 import android.os.Environment;
50 import android.os.Handler;
51 import android.preference.PreferenceManager;
52 import android.print.PrintDocumentAdapter;
53 import android.print.PrintManager;
54 import android.support.annotation.NonNull;
55 import android.support.design.widget.CoordinatorLayout;
56 import android.support.design.widget.FloatingActionButton;
57 import android.support.design.widget.NavigationView;
58 import android.support.design.widget.Snackbar;
59 import android.support.v4.app.ActivityCompat;
60 import android.support.v4.content.ContextCompat;
61 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
62 import android.support.v4.content.pm.ShortcutInfoCompat;
63 import android.support.v4.content.pm.ShortcutManagerCompat;
64 import android.support.v4.graphics.drawable.IconCompat;
65 import android.support.v4.view.GravityCompat;
66 import android.support.v4.widget.DrawerLayout;
67 import android.support.v4.widget.SwipeRefreshLayout;
68 import android.support.v7.app.ActionBar;
69 import android.support.v7.app.ActionBarDrawerToggle;
70 import android.support.v7.app.AppCompatActivity;
71 import android.support.v7.app.AppCompatDialogFragment;
72 import android.support.v7.widget.Toolbar;
73 import android.text.Editable;
74 import android.text.Spanned;
75 import android.text.TextWatcher;
76 import android.text.style.ForegroundColorSpan;
77 import android.util.Patterns;
78 import android.view.ContextMenu;
79 import android.view.GestureDetector;
80 import android.view.KeyEvent;
81 import android.view.Menu;
82 import android.view.MenuItem;
83 import android.view.MotionEvent;
84 import android.view.View;
85 import android.view.ViewGroup;
86 import android.view.WindowManager;
87 import android.view.inputmethod.InputMethodManager;
88 import android.webkit.CookieManager;
89 import android.webkit.HttpAuthHandler;
90 import android.webkit.SslErrorHandler;
91 import android.webkit.ValueCallback;
92 import android.webkit.WebBackForwardList;
93 import android.webkit.WebChromeClient;
94 import android.webkit.WebResourceResponse;
95 import android.webkit.WebStorage;
96 import android.webkit.WebView;
97 import android.webkit.WebViewClient;
98 import android.webkit.WebViewDatabase;
99 import android.widget.ArrayAdapter;
100 import android.widget.CursorAdapter;
101 import android.widget.EditText;
102 import android.widget.FrameLayout;
103 import android.widget.ImageView;
104 import android.widget.LinearLayout;
105 import android.widget.ListView;
106 import android.widget.ProgressBar;
107 import android.widget.RadioButton;
108 import android.widget.RelativeLayout;
109 import android.widget.TextView;
111 import com.stoutner.privacybrowser.BuildConfig;
112 import com.stoutner.privacybrowser.R;
113 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
114 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
116 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
117 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
118 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
119 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
120 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
121 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
122 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
123 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
124 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
125 import com.stoutner.privacybrowser.helpers.AdHelper;
126 import com.stoutner.privacybrowser.helpers.BlockListHelper;
127 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
128 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
129 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
130 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
131 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
133 import java.io.ByteArrayInputStream;
134 import java.io.ByteArrayOutputStream;
136 import java.io.IOException;
137 import java.io.UnsupportedEncodingException;
138 import java.net.MalformedURLException;
140 import java.net.URLDecoder;
141 import java.net.URLEncoder;
142 import java.util.ArrayList;
143 import java.util.Date;
144 import java.util.HashMap;
145 import java.util.HashSet;
146 import java.util.List;
147 import java.util.Map;
148 import java.util.Set;
150 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
151 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
152 CreateHomeScreenShortcutDialog.CreateHomeScreenShortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
153 DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
154 HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
155 SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
157 // `darkTheme` is public static so it can be accessed from everywhere.
158 public static boolean darkTheme;
160 // `allowScreenshots` is public static so it can be accessed from everywhere. It is also used in `onCreate()`.
161 public static boolean allowScreenshots;
163 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
164 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
165 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
166 public static Bitmap favoriteIconBitmap;
168 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
169 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
170 public static String formattedUrlString;
172 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
173 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
174 public static SslCertificate sslCertificate;
176 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
177 public static String orbotStatus;
179 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
180 public static String webViewTitle;
182 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
183 public static String appliedUserAgentString;
185 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
186 public static boolean reloadOnRestart;
188 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`. It is also used in `onRestart()`.
189 public static boolean loadUrlOnRestart;
191 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
192 public static boolean restartFromBookmarksActivity;
194 // The block list versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
195 public static String easyListVersion;
196 public static String easyPrivacyVersion;
197 public static String fanboysAnnoyanceVersion;
198 public static String fanboysSocialVersion;
200 // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`. They are also used in `onCreate()`.
201 public static List<String[]> resourceRequests;
202 public static String[] whiteListResultStringArray;
203 public final static int REQUEST_DISPOSITION = 0;
204 public final static int REQUEST_URL = 1;
205 public final static int REQUEST_BLOCKLIST = 2;
206 public final static int REQUEST_SUBLIST = 3;
207 public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
208 public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
210 public final static int REQUEST_DEFAULT = 0;
211 public final static int REQUEST_ALLOWED = 1;
212 public final static int REQUEST_THIRD_PARTY = 2;
213 public final static int REQUEST_BLOCKED = 3;
215 public final static int MAIN_WHITELIST = 1;
216 public final static int FINAL_WHITELIST = 2;
217 public final static int DOMAIN_WHITELIST = 3;
218 public final static int DOMAIN_INITIAL_WHITELIST = 4;
219 public final static int DOMAIN_FINAL_WHITELIST = 5;
220 public final static int THIRD_PARTY_WHITELIST = 6;
221 public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
222 public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
224 public final static int MAIN_BLACKLIST = 9;
225 public final static int INITIAL_BLACKLIST = 10;
226 public final static int FINAL_BLACKLIST = 11;
227 public final static int DOMAIN_BLACKLIST = 12;
228 public final static int DOMAIN_INITIAL_BLACKLIST = 13;
229 public final static int DOMAIN_FINAL_BLACKLIST = 14;
230 public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
231 public final static int THIRD_PARTY_BLACKLIST = 16;
232 public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
233 public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
234 public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
235 public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
236 public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
237 public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
239 // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
240 // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
241 public static boolean blockAllThirdPartyRequests;
243 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
244 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
245 public static String currentBookmarksFolder;
247 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
248 public static int domainSettingsDatabaseId;
250 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
251 public static String pinnedDomainSslIssuedToCNameString;
252 public static String pinnedDomainSslIssuedToONameString;
253 public static String pinnedDomainSslIssuedToUNameString;
254 public static String pinnedDomainSslIssuedByCNameString;
255 public static String pinnedDomainSslIssuedByONameString;
256 public static String pinnedDomainSslIssuedByUNameString;
257 public static Date pinnedDomainSslStartDate;
258 public static Date pinnedDomainSslEndDate;
260 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
261 public final static int UNRECOGNIZED_USER_AGENT = -1;
262 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
263 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
264 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
265 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
266 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
269 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
270 private ActionBar appBar;
272 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
273 private boolean navigatingHistory;
275 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
276 private Bitmap favoriteIconDefaultBitmap;
278 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
279 private DrawerLayout drawerLayout;
281 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
282 private CoordinatorLayout rootCoordinatorLayout;
284 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
285 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
286 private WebView mainWebView;
288 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
289 private FrameLayout fullScreenVideoFrameLayout;
291 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
292 private SwipeRefreshLayout swipeRefreshLayout;
294 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
295 private RelativeLayout urlAppBarRelativeLayout;
297 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
298 private ImageView favoriteIconImageView;
300 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
301 private CookieManager cookieManager;
303 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
304 private final Map<String, String> customHeaders = new HashMap<>();
306 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
307 private boolean javaScriptEnabled;
309 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
310 private boolean firstPartyCookiesEnabled;
312 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
313 private boolean thirdPartyCookiesEnabled;
315 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
316 private boolean domStorageEnabled;
318 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`. It can be removed once the minimum API >= 26.
319 private boolean saveFormDataEnabled;
321 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
322 private boolean nightMode;
324 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
325 private boolean displayWebpageImagesBoolean;
327 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
328 private String homepage;
330 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
331 private String searchURL;
333 // The block list variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
334 private boolean easyListEnabled;
335 private boolean easyPrivacyEnabled;
336 private boolean fanboysAnnoyanceListEnabled;
337 private boolean fanboysSocialBlockingListEnabled;
339 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
340 private Runtime privacyBrowserRuntime;
342 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
343 private boolean proxyThroughOrbot;
345 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
346 private boolean incognitoModeEnabled;
348 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
349 private boolean fullScreenBrowsingModeEnabled;
351 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
352 private boolean inFullScreenBrowsingMode;
354 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
355 private boolean hideSystemBarsOnFullscreen;
357 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
358 private boolean translucentNavigationBarOnFullscreen;
360 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
361 private boolean reapplyDomainSettingsOnRestart;
363 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
364 private boolean reapplyAppSettingsOnRestart;
366 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
367 private String currentDomainName;
369 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
370 private boolean ignorePinnedSslCertificate;
372 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
373 private boolean waitingForOrbot;
375 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
376 private boolean domainSettingsApplied;
378 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
379 private int displayWebpageImagesInt;
381 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
382 private boolean onTheFlyDisplayImagesSet;
384 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
385 private String waitingForOrbotHTMLString;
387 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
388 private String privateDataDirectoryString;
390 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
391 private LinearLayout findOnPageLinearLayout;
393 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
394 private EditText findOnPageEditText;
396 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
397 private Menu mainMenu;
399 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
400 private ActionBarDrawerToggle drawerToggle;
402 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
403 private Toolbar supportAppBar;
405 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
406 private EditText urlTextBox;
408 // The color spans are used in `onCreate()` and `highlightUrlText()`.
409 private ForegroundColorSpan redColorSpan;
410 private ForegroundColorSpan initialGrayColorSpan;
411 private ForegroundColorSpan finalGrayColorSpan;
413 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
414 private SslErrorHandler sslErrorHandler;
416 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
417 private static HttpAuthHandler httpAuthHandler;
419 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
420 private InputMethodManager inputMethodManager;
422 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
423 private RelativeLayout mainWebViewRelativeLayout;
425 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
426 private boolean urlIsLoading;
428 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
429 private boolean pinnedDomainSslCertificate;
431 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
432 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
434 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
435 private ListView bookmarksListView;
437 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
438 private TextView bookmarksTitleTextView;
440 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
441 private Cursor bookmarksCursor;
443 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
444 private CursorAdapter bookmarksCursorAdapter;
446 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
447 private String oldFolderNameString;
449 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
450 private ValueCallback<Uri[]> fileChooserCallback;
452 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
453 private String downloadUrl;
454 private String downloadContentDisposition;
455 private long downloadContentLength;
457 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
458 private String downloadImageUrl;
460 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
461 private ArrayAdapter<CharSequence> userAgentNamesArray;
462 private String[] userAgentDataArray;
464 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
465 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
466 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
469 // 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.
470 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
471 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
472 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
473 @SuppressWarnings("deprecation")
474 protected void onCreate(Bundle savedInstanceState) {
475 // Get a handle for the shared preferences.
476 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
478 // Get the theme and screenshot preferences.
479 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
480 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
482 // Disable screenshots if not allowed.
483 if (!allowScreenshots) {
484 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
487 // Set the activity theme.
489 setTheme(R.style.PrivacyBrowserDark);
491 setTheme(R.style.PrivacyBrowserLight);
494 // Run the default commands.
495 super.onCreate(savedInstanceState);
497 // Set the content view.
498 setContentView(R.layout.main_drawerlayout);
500 // Get a handle for `inputMethodManager`.
501 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
503 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
504 supportAppBar = findViewById(R.id.app_bar);
505 setSupportActionBar(supportAppBar);
506 appBar = getSupportActionBar();
508 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
509 assert appBar != null;
511 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
512 appBar.setCustomView(R.layout.url_app_bar);
513 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
515 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
516 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
517 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
518 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
520 // Get a handle for `urlTextBox`.
521 urlTextBox = findViewById(R.id.url_edittext);
523 // Remove the formatting from `urlTextBar` when the user is editing the text.
524 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
525 if (hasFocus) { // The user is editing `urlTextBox`.
526 // Remove the highlighting.
527 urlTextBox.getText().removeSpan(redColorSpan);
528 urlTextBox.getText().removeSpan(initialGrayColorSpan);
529 urlTextBox.getText().removeSpan(finalGrayColorSpan);
530 } else { // The user has stopped editing `urlTextBox`.
531 // Reapply the highlighting.
536 // Set the go button on the keyboard to load the URL in `urlTextBox`.
537 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
538 // If the event is a key-down event on the `enter` button, load the URL.
539 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
540 // Load the URL into the mainWebView and consume the event.
542 loadUrlFromTextBox();
543 } catch (UnsupportedEncodingException e) {
546 // If the enter key was pressed, consume the event.
549 // If any other key was pressed, do not consume the event.
554 // Set `waitingForOrbotHTMLString`.
555 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
557 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
558 currentDomainName = "";
559 orbotStatus = "unknown";
560 waitingForOrbot = false;
562 // Create an Orbot status `BroadcastReceiver`.
563 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
565 public void onReceive(Context context, Intent intent) {
566 // Store the content of the status message in `orbotStatus`.
567 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
569 // If we are waiting on Orbot, load the website now that Orbot is connected.
570 if (orbotStatus.equals("ON") && waitingForOrbot) {
571 // Reset `waitingForOrbot`.
572 waitingForOrbot = false;
574 // Load `formattedUrlString
575 loadUrl(formattedUrlString);
580 // Register `orbotStatusBroadcastReceiver` on `this` context.
581 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
583 // Get handles for views that need to be accessed.
584 drawerLayout = findViewById(R.id.drawerlayout);
585 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
586 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
587 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
588 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
589 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
590 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
591 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
592 mainWebView = findViewById(R.id.main_webview);
593 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
594 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
595 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
596 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
597 favoriteIconImageView = findViewById(R.id.favorite_icon);
599 // 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.
601 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
602 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
603 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
604 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
606 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
607 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
608 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
609 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
612 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
613 launchBookmarksActivityFab.setOnClickListener(v -> {
614 // Create an intent to launch the bookmarks activity.
615 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
617 // Include the current folder with the `Intent`.
618 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
621 startActivity(bookmarksIntent);
624 // Set the create new bookmark folder FAB to display an alert dialog.
625 createBookmarkFolderFab.setOnClickListener(v -> {
626 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
627 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
628 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
631 // Set the create new bookmark FAB to display an alert dialog.
632 createBookmarkFab.setOnClickListener(view -> {
633 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
634 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
635 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
638 // Create a double-tap listener to toggle full-screen mode.
639 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
640 // Override `onDoubleTap()`. All other events are handled using the default settings.
642 public boolean onDoubleTap(MotionEvent event) {
643 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
644 // Toggle `inFullScreenBrowsingMode`.
645 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
647 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
648 // Hide the `appBar`.
651 // Hide the banner ad in the free flavor.
652 if (BuildConfig.FLAVOR.contentEquals("free")) {
653 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
654 AdHelper.hideAd(findViewById(R.id.adview));
657 // Modify the system bars.
658 if (hideSystemBarsOnFullscreen) { // Hide everything.
659 // Remove the translucent overlays.
660 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
662 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
663 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
665 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
666 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
667 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
669 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
671 // Set `rootCoordinatorLayout` to fill the whole screen.
672 rootCoordinatorLayout.setFitsSystemWindows(false);
673 } else { // Hide everything except the status and navigation bars.
674 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
675 rootCoordinatorLayout.setFitsSystemWindows(false);
677 // 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.
678 if (translucentNavigationBarOnFullscreen) {
679 // Set the navigation bar to be translucent.
680 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
683 } else { // Switch to normal viewing mode.
684 // Show the `appBar`.
687 // Show the `BannerAd` in the free flavor.
688 if (BuildConfig.FLAVOR.contentEquals("free")) {
689 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
690 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
693 // Remove the translucent navigation bar flag if it is set.
694 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
696 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
697 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
699 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
700 rootCoordinatorLayout.setSystemUiVisibility(0);
702 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
703 rootCoordinatorLayout.setFitsSystemWindows(true);
706 // Consume the double-tap.
708 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
714 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
715 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
716 // Call `performClick()` on the view, which is required for accessibility.
719 // Send the `event` to `gestureDetector`.
720 return gestureDetector.onTouchEvent(event);
723 // Update `findOnPageCountTextView`.
724 mainWebView.setFindListener(new WebView.FindListener() {
725 // Get a handle for `findOnPageCountTextView`.
726 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
729 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
730 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
731 // Set `findOnPageCountTextView` to `0/0`.
732 findOnPageCountTextView.setText(R.string.zero_of_zero);
733 } else if (isDoneCounting) { // There are matches.
734 // `activeMatchOrdinal` is zero-based.
735 int activeMatch = activeMatchOrdinal + 1;
737 // Build the match string.
738 String matchString = activeMatch + "/" + numberOfMatches;
740 // Set `findOnPageCountTextView`.
741 findOnPageCountTextView.setText(matchString);
746 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
747 findOnPageEditText.addTextChangedListener(new TextWatcher() {
749 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
754 public void onTextChanged(CharSequence s, int start, int before, int count) {
759 public void afterTextChanged(Editable s) {
760 // Search for the text in `mainWebView`.
761 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
765 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
766 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
767 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
768 // Hide the soft keyboard. `0` indicates no additional flags.
769 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
771 // Consume the event.
773 } else { // A different key was pressed.
774 // Do not consume the event.
779 // Implement swipe to refresh
780 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
781 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
782 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
784 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
785 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
786 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
788 // Listen for touches on the navigation menu.
789 final NavigationView navigationView = findViewById(R.id.navigationview);
790 navigationView.setNavigationItemSelectedListener(this);
792 // 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.
793 final Menu navigationMenu = navigationView.getMenu();
794 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
795 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
796 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
797 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
799 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
800 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
801 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
803 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
804 currentBookmarksFolder = "";
806 // Load the home folder, which is `""` in the database.
807 loadBookmarksFolder();
809 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
810 // Convert the id from long to int to match the format of the bookmarks database.
811 int databaseID = (int) id;
813 // Get the bookmark cursor for this ID and move it to the first row.
814 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
815 bookmarkCursor.moveToFirst();
817 // Act upon the bookmark according to the type.
818 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
819 // Store the new folder name in `currentBookmarksFolder`.
820 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
822 // Load the new folder.
823 loadBookmarksFolder();
824 } else { // The selected bookmark is not a folder.
825 // Load the bookmark URL.
826 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
828 // Close the bookmarks drawer.
829 drawerLayout.closeDrawer(GravityCompat.END);
832 // Close the `Cursor`.
833 bookmarkCursor.close();
836 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
837 // Convert the database ID from `long` to `int`.
838 int databaseId = (int) id;
840 // Find out if the selected bookmark is a folder.
841 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
844 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
845 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
847 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
848 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
849 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
851 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
852 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
853 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
856 // Consume the event.
860 // The `DrawerListener` is used to update the Navigation Menu.
861 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
863 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
867 public void onDrawerOpened(@NonNull View drawerView) {
871 public void onDrawerClosed(@NonNull View drawerView) {
875 public void onDrawerStateChanged(int newState) {
876 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
877 // Initialize a the blocked requests counter.
878 int blockedRequests = 0;
880 // Count the number of blocked requests.
881 for (int i = 0; i < resourceRequests.size(); i++) {
882 // Add the blocked requests.
883 if (Integer.valueOf(resourceRequests.get(i)[REQUEST_DISPOSITION]) == REQUEST_BLOCKED) {
887 // Add the third-party requests if they are blocked.
888 if (blockAllThirdPartyRequests && (Integer.valueOf(resourceRequests.get(i)[REQUEST_DISPOSITION]) == REQUEST_THIRD_PARTY)) {
893 // Update the back, forward, history, and requests menu items.
894 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
895 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
896 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
897 navigationRequestsMenuItem.setTitle(getResources().getString(R.string.requests) + " - " + blockedRequests);
899 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
900 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
902 // Clear the focus from `urlTextBox` if it has it.
903 urlTextBox.clearFocus();
908 // drawerToggle creates the hamburger icon at the start of the AppBar.
909 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
911 // Get a handle for the progress bar.
912 final ProgressBar progressBar = findViewById(R.id.progress_bar);
914 mainWebView.setWebChromeClient(new WebChromeClient() {
915 // Update the progress bar when a page is loading.
917 public void onProgressChanged(WebView view, int progress) {
918 // Inject the night mode CSS if night mode is enabled.
920 // `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
921 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
922 // `border: none` removes all borders, which can also be used to underline text.
923 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
924 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
925 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
926 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
927 // Initialize a `Handler` to display `mainWebView`.
928 Handler displayWebViewHandler = new Handler();
930 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
931 Runnable displayWebViewRunnable = () -> {
932 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
933 if (progressBar.getVisibility() == View.GONE) {
934 mainWebView.setVisibility(View.VISIBLE);
938 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
939 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
943 // Update the progress bar.
944 progressBar.setProgress(progress);
946 // Set the visibility of the progress bar.
947 if (progress < 100) {
948 // Show the progress bar.
949 progressBar.setVisibility(View.VISIBLE);
951 // Hide the progress bar.
952 progressBar.setVisibility(View.GONE);
954 // Display `mainWebView` if night mode is disabled.
955 // 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
956 // currently enabled.
958 mainWebView.setVisibility(View.VISIBLE);
961 //Stop the swipe to refresh indicator if it is running
962 swipeRefreshLayout.setRefreshing(false);
966 // Set the favorite icon when it changes.
968 public void onReceivedIcon(WebView view, Bitmap icon) {
969 // Only update the favorite icon if the website has finished loading.
970 if (progressBar.getVisibility() == View.GONE) {
971 // Save a copy of the favorite icon.
972 favoriteIconBitmap = icon;
974 // Place the favorite icon in the appBar.
975 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
979 // Save a copy of the title when it changes.
981 public void onReceivedTitle(WebView view, String title) {
982 // Save a copy of the title.
983 webViewTitle = title;
986 // Enter full screen video.
988 public void onShowCustomView(View view, CustomViewCallback callback) {
989 // Pause the ad if this is the free flavor.
990 if (BuildConfig.FLAVOR.contentEquals("free")) {
991 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
992 AdHelper.pauseAd(findViewById(R.id.adview));
995 // Remove the translucent overlays.
996 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
998 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
999 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1001 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1002 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1003 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1005 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1007 // Set `rootCoordinatorLayout` to fill the entire screen.
1008 rootCoordinatorLayout.setFitsSystemWindows(false);
1010 // Disable the sliding drawers.
1011 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1013 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1014 fullScreenVideoFrameLayout.addView(view);
1015 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1018 // Exit full screen video.
1020 public void onHideCustomView() {
1021 // Hide `fullScreenVideoFrameLayout`.
1022 fullScreenVideoFrameLayout.removeAllViews();
1023 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1025 // Enable the sliding drawers.
1026 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1028 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1029 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1031 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1032 rootCoordinatorLayout.setFitsSystemWindows(true);
1034 // Show the ad if this is the free flavor.
1035 if (BuildConfig.FLAVOR.contentEquals("free")) {
1036 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1037 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1043 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1044 // Show the file chooser if the device is running API >= 21.
1045 if (Build.VERSION.SDK_INT >= 21) {
1046 // Store the file path callback.
1047 fileChooserCallback = filePathCallback;
1049 // Create an intent to open a chooser based ont the file chooser parameters.
1050 Intent fileChooserIntent = fileChooserParams.createIntent();
1052 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1053 startActivityForResult(fileChooserIntent, 0);
1059 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1060 registerForContextMenu(mainWebView);
1062 // Allow the downloading of files.
1063 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1064 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1065 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1066 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1068 // Store the variables for future use by `onRequestPermissionsResult()`.
1070 downloadContentDisposition = contentDisposition;
1071 downloadContentLength = contentLength;
1073 // Show a dialog if the user has previously denied the permission.
1074 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1075 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1076 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1078 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1079 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1080 } else { // Show the permission request directly.
1081 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1082 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1084 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1085 // Get a handle for the download file alert dialog.
1086 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1088 // Show the download file alert dialog.
1089 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1093 // Allow pinch to zoom.
1094 mainWebView.getSettings().setBuiltInZoomControls(true);
1096 // Hide zoom controls.
1097 mainWebView.getSettings().setDisplayZoomControls(false);
1099 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1100 mainWebView.getSettings().setUseWideViewPort(true);
1102 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1103 mainWebView.getSettings().setLoadWithOverviewMode(true);
1105 // Explicitly disable geolocation.
1106 mainWebView.getSettings().setGeolocationEnabled(false);
1108 // Initialize cookieManager.
1109 cookieManager = CookieManager.getInstance();
1111 // 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).
1112 customHeaders.put("X-Requested-With", "");
1114 // Initialize the default preference values the first time the program is run. `this` is the context. `false` keeps this command from resetting any current preferences back to default.
1115 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1117 // Get the intent that started the app.
1118 final Intent launchingIntent = getIntent();
1120 // Extract the launching intent data as `launchingIntentUriData`.
1121 final Uri launchingIntentUriData = launchingIntent.getData();
1123 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1124 if (launchingIntentUriData != null) {
1125 formattedUrlString = launchingIntentUriData.toString();
1128 // Get a handle for the `Runtime`.
1129 privacyBrowserRuntime = Runtime.getRuntime();
1131 // Store the application's private data directory.
1132 privateDataDirectoryString = getApplicationInfo().dataDir;
1133 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1135 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1136 inFullScreenBrowsingMode = false;
1138 // Initialize the privacy settings variables.
1139 javaScriptEnabled = false;
1140 firstPartyCookiesEnabled = false;
1141 thirdPartyCookiesEnabled = false;
1142 domStorageEnabled = false;
1143 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1146 // Initialize the WebView title.
1147 webViewTitle = getString(R.string.no_title);
1149 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1150 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1151 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1152 assert favoriteIconBitmapDrawable != null;
1153 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1155 // If the favorite icon is null, load the default.
1156 if (favoriteIconBitmap == null) {
1157 favoriteIconBitmap = favoriteIconDefaultBitmap;
1160 // Initialize the user agent array adapter and string array.
1161 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1162 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1164 // Apply the app settings from the shared preferences.
1167 // Instantiate the block list helper.
1168 BlockListHelper blockListHelper = new BlockListHelper();
1170 // Initialize the list of resource requests.
1171 resourceRequests = new ArrayList<>();
1173 // Parse the block lists.
1174 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1175 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1176 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1177 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1179 // Store the list versions.
1180 easyListVersion = easyList.get(0).get(0)[0];
1181 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1182 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1183 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1185 mainWebView.setWebViewClient(new WebViewClient() {
1186 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1187 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1188 @SuppressWarnings("deprecation")
1190 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1191 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1192 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1193 applyDomainSettings(url, true, false);
1195 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1197 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1198 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1199 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1201 // Parse the url and set it as the data for the intent.
1202 emailIntent.setData(Uri.parse(url));
1204 // Open the email program in a new task instead of as part of Privacy Browser.
1205 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1208 startActivity(emailIntent);
1210 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1212 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1213 // Open the dialer and load the phone number, but wait for the user to place the call.
1214 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1216 // Add the phone number to the intent.
1217 dialIntent.setData(Uri.parse(url));
1219 // Open the dialer in a new task instead of as part of Privacy Browser.
1220 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1223 startActivity(dialIntent);
1225 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1227 } else { // Load a system chooser to select an app that can handle the URL.
1228 // Open an app that can handle the URL.
1229 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1231 // Add the URL to the intent.
1232 genericIntent.setData(Uri.parse(url));
1234 // List all apps that can handle the URL instead of just opening the first one.
1235 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1237 // Open the app in a new task instead of as part of Privacy Browser.
1238 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1240 // Start the app or display a snackbar if no app is available to handle the URL.
1242 startActivity(genericIntent);
1243 } catch (ActivityNotFoundException exception) {
1244 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1247 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1252 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1253 @SuppressWarnings("deprecation")
1255 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1256 // Create an empty web resource response to be used if the resource request is blocked.
1257 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1259 // Reset `whiteListResultStringArray`.
1260 whiteListResultStringArray = null;
1262 // Initialize the third party request tracker.
1263 boolean isThirdPartyRequest = false;
1266 String currentDomain = "";
1268 // Nobody is happy when comparing null strings.
1269 if (!(formattedUrlString == null) && !(url == null)) {
1270 // Get the domain strings to URIs.
1271 Uri currentDomainUri = Uri.parse(formattedUrlString);
1272 Uri requestDomainUri = Uri.parse(url);
1274 // Get the domain host names.
1275 String currentBaseDomain = currentDomainUri.getHost();
1276 String requestBaseDomain = requestDomainUri.getHost();
1278 // Update the current domain variable.
1279 currentDomain = currentBaseDomain;
1281 // Only compare the current base domain and the request base domain if neither is null.
1282 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1283 // Determine the current base domain.
1284 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1285 // Remove the first subdomain.
1286 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1289 // Determine the request base domain.
1290 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1291 // Remove the first subdomain.
1292 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1295 // Update the third party request tracker.
1296 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1300 // Block third-party requests if enabled.
1301 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1302 // Add the request to the log.
1303 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1305 // Return an empty web resource response.
1306 return emptyWebResourceResponse;
1309 // Check EasyList if it is enabled.
1310 if (easyListEnabled) {
1311 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1312 // The resource request was blocked. Return an empty web resource response.
1313 return emptyWebResourceResponse;
1317 // Check EasyPrivacy if it is enabled.
1318 if (easyPrivacyEnabled) {
1319 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1320 // The resource request was blocked. Return an empty web resource response.
1321 return emptyWebResourceResponse;
1325 // Check Fanboy’s Annoyance List if it is enabled.
1326 if (fanboysAnnoyanceListEnabled) {
1327 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1328 // The resource request was blocked. Return an empty web resource response.
1329 return emptyWebResourceResponse;
1331 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1332 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1333 // The resource request was blocked. Return an empty web resource response.
1334 return emptyWebResourceResponse;
1338 // Add the request to the log because it hasn't been processed by any of the previous checks.
1339 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1340 resourceRequests.add(whiteListResultStringArray);
1341 } else { // The request didn't match any blocklist entry. Log it as a defult request.
1342 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1345 // The resource request has not been blocked. `return null` loads the requested resource.
1349 // Handle HTTP authentication requests.
1351 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1352 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1353 httpAuthHandler = handler;
1355 // Display the HTTP authentication dialog.
1356 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1357 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1360 // Update the URL in urlTextBox when the page starts to load.
1362 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1363 // Reset the list of resource requests.
1364 resourceRequests.clear();
1366 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1368 mainWebView.setVisibility(View.INVISIBLE);
1371 // Hide the keyboard. `0` indicates no additional flags.
1372 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1374 // Check to see if Privacy Browser is waiting on Orbot.
1375 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1376 // 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.
1377 formattedUrlString = url;
1379 // Display the formatted URL text.
1380 urlTextBox.setText(formattedUrlString);
1382 // Apply text highlighting to `urlTextBox`.
1385 // Apply any custom domain settings if the URL was loaded by navigating history.
1386 if (navigatingHistory) {
1387 // Reset `navigatingHistory`.
1388 navigatingHistory = false;
1390 // Apply the domain settings.
1391 applyDomainSettings(url, true, false);
1394 // 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.
1395 urlIsLoading = true;
1399 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1401 public void onPageFinished(WebView view, String url) {
1402 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1403 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1404 cookieManager.flush();
1407 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1408 urlIsLoading = false;
1410 // Clear the cache and history if Incognito Mode is enabled.
1411 if (incognitoModeEnabled) {
1412 // Clear the cache. `true` includes disk files.
1413 mainWebView.clearCache(true);
1415 // Clear the back/forward history.
1416 mainWebView.clearHistory();
1418 // Manually delete cache folders.
1420 // Delete the main cache directory.
1421 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1423 // Delete the secondary `Service Worker` cache directory.
1424 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1425 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1426 } catch (IOException e) {
1427 // Do nothing if an error is thrown.
1431 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1432 if (!waitingForOrbot) {
1433 // Check to see if `WebView` has set `url` to be `about:blank`.
1434 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1435 // Set `formattedUrlString` to `""`.
1436 formattedUrlString = "";
1438 urlTextBox.setText(formattedUrlString);
1440 // Request focus for `urlTextBox`.
1441 urlTextBox.requestFocus();
1443 // Display the keyboard.
1444 inputMethodManager.showSoftInput(urlTextBox, 0);
1446 // Apply the domain settings. This clears any settings from the previous domain.
1447 applyDomainSettings(formattedUrlString, true, false);
1448 } else { // `WebView` has loaded a webpage.
1449 // Set `formattedUrlString`.
1450 formattedUrlString = url;
1452 // Only update `urlTextBox` if the user is not typing in it.
1453 if (!urlTextBox.hasFocus()) {
1454 // Display the formatted URL text.
1455 urlTextBox.setText(formattedUrlString);
1457 // Apply text highlighting to `urlTextBox`.
1462 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1463 sslCertificate = mainWebView.getCertificate();
1465 // 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.
1466 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1467 // Initialize the current SSL certificate variables.
1468 String currentWebsiteIssuedToCName = "";
1469 String currentWebsiteIssuedToOName = "";
1470 String currentWebsiteIssuedToUName = "";
1471 String currentWebsiteIssuedByCName = "";
1472 String currentWebsiteIssuedByOName = "";
1473 String currentWebsiteIssuedByUName = "";
1474 Date currentWebsiteSslStartDate = null;
1475 Date currentWebsiteSslEndDate = null;
1478 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1479 if (sslCertificate != null) {
1480 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1481 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1482 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1483 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1484 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1485 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1486 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1487 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1490 // 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`.
1491 String currentWebsiteSslStartDateString = "";
1492 String currentWebsiteSslEndDateString = "";
1493 String pinnedDomainSslStartDateString = "";
1494 String pinnedDomainSslEndDateString = "";
1496 // Convert the `Dates` to `Strings` if they are not `null`.
1497 if (currentWebsiteSslStartDate != null) {
1498 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1501 if (currentWebsiteSslEndDate != null) {
1502 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1505 if (pinnedDomainSslStartDate != null) {
1506 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1509 if (pinnedDomainSslEndDate != null) {
1510 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1513 // Check to see if the pinned SSL certificate matches the current website certificate.
1514 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1515 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1516 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1517 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1518 // The pinned SSL certificate doesn't match the current domain certificate.
1519 //Display the pinned SSL certificate mismatch `AlertDialog`.
1520 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1521 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1527 // Handle SSL Certificate errors.
1529 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1530 // Get the current website SSL certificate.
1531 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1533 // Extract the individual pieces of information from the current website SSL certificate.
1534 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1535 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1536 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1537 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1538 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1539 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1540 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1541 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1543 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1544 if (pinnedDomainSslCertificate &&
1545 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1546 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1547 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1548 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1549 // An SSL certificate is pinned and matches the current domain certificate.
1550 // Proceed to the website without displaying an error.
1552 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1553 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1554 sslErrorHandler = handler;
1556 // Display the SSL error `AlertDialog`.
1557 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1558 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1563 // Load the website if not waiting for Orbot to connect.
1564 if (!waitingForOrbot) {
1565 loadUrl(formattedUrlString);
1570 protected void onNewIntent(Intent intent) {
1571 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1574 // Check to see if the intent contains a new URL.
1575 if (intent.getData() != null) {
1576 // Get the intent data.
1577 final Uri intentUriData = intent.getData();
1579 // Load the website.
1580 loadUrl(intentUriData.toString());
1582 // Close the navigation drawer if it is open.
1583 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1584 drawerLayout.closeDrawer(GravityCompat.START);
1587 // Close the bookmarks drawer if it is open.
1588 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1589 drawerLayout.closeDrawer(GravityCompat.END);
1592 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1593 mainWebView.requestFocus();
1598 public void onRestart() {
1599 // Run the default commands.
1602 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1603 if (proxyThroughOrbot) {
1604 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1605 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1607 // Send the intent to the Orbot package.
1608 orbotIntent.setPackage("org.torproject.android");
1611 sendBroadcast(orbotIntent);
1614 // Apply the app settings if returning from the Settings activity..
1615 if (reapplyAppSettingsOnRestart) {
1616 // Apply the app settings.
1619 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1620 if (reloadOnRestart) {
1621 // Reload `mainWebView`.
1622 mainWebView.reload();
1624 // Reset `reloadOnRestartBoolean`.
1625 reloadOnRestart = false;
1628 // Reset the return from settings flag.
1629 reapplyAppSettingsOnRestart = false;
1632 // Apply the domain settings if returning from the Domains activity.
1633 if (reapplyDomainSettingsOnRestart) {
1634 // Reapply the domain settings.
1635 applyDomainSettings(formattedUrlString, false, true);
1637 // Reset `reapplyDomainSettingsOnRestart`.
1638 reapplyDomainSettingsOnRestart = false;
1641 // Load the URL on restart to apply changes to night mode.
1642 if (loadUrlOnRestart) {
1643 // Load the current `formattedUrlString`.
1644 loadUrl(formattedUrlString);
1646 // Reset `loadUrlOnRestart.
1647 loadUrlOnRestart = false;
1650 // Update the bookmarks drawer if returning from the Bookmarks activity.
1651 if (restartFromBookmarksActivity) {
1652 // Close the bookmarks drawer.
1653 drawerLayout.closeDrawer(GravityCompat.END);
1655 // Reload the bookmarks drawer.
1656 loadBookmarksFolder();
1658 // Reset `restartFromBookmarksActivity`.
1659 restartFromBookmarksActivity = false;
1662 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1663 updatePrivacyIcons(true);
1666 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1668 public void onResume() {
1669 // Run the default commands.
1672 // Resume JavaScript (if enabled).
1673 mainWebView.resumeTimers();
1675 // Resume `mainWebView`.
1676 mainWebView.onResume();
1678 // Resume the adView for the free flavor.
1679 if (BuildConfig.FLAVOR.contentEquals("free")) {
1680 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1681 AdHelper.resumeAd(findViewById(R.id.adview));
1686 public void onPause() {
1687 // Pause `mainWebView`.
1688 mainWebView.onPause();
1690 // Stop all JavaScript.
1691 mainWebView.pauseTimers();
1693 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1694 if (BuildConfig.FLAVOR.contentEquals("free")) {
1695 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1696 AdHelper.pauseAd(findViewById(R.id.adview));
1703 public boolean onCreateOptionsMenu(Menu menu) {
1704 // Inflate the menu; this adds items to the action bar if it is present.
1705 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1707 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1710 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1711 updatePrivacyIcons(false);
1713 // Get handles for the menu items.
1714 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1715 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1716 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1717 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1718 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1719 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1720 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1722 // Only display third-party cookies if API >= 21
1723 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1725 // Only display the form data menu items if the API < 26.
1726 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1727 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1729 // Only show Ad Consent if this is the free flavor.
1730 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1732 // Get the shared preference values. `this` references the current context.
1733 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1735 // 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.
1736 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1737 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1738 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1739 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1740 } else { //Do not display the additional icons.
1741 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1742 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1743 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1750 public boolean onPrepareOptionsMenu(Menu menu) {
1751 // Get handles for the menu items.
1752 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1753 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1754 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1755 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1756 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1757 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1758 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1759 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1760 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1761 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1762 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1763 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1764 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1765 MenuItem blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1766 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1767 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1768 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1770 // Set the text for the domain menu item.
1771 if (domainSettingsApplied) {
1772 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1774 addOrEditDomain.setTitle(R.string.add_domain_settings);
1777 // Set the status of the menu item checkboxes.
1778 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1779 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1780 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1781 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
1782 easyListMenuItem.setChecked(easyListEnabled);
1783 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1784 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1785 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1786 blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1787 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1788 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1790 // Enable third-party cookies if first-party cookies are enabled.
1791 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1793 // Enable DOM Storage if JavaScript is enabled.
1794 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1796 // Enable Clear Cookies if there are any.
1797 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1799 // Get a count of the number of files in the Local Storage directory.
1800 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1801 int localStorageDirectoryNumberOfFiles = 0;
1802 if (localStorageDirectory.exists()) {
1803 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1806 // Get a count of the number of files in the IndexedDB directory.
1807 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1808 int indexedDBDirectoryNumberOfFiles = 0;
1809 if (indexedDBDirectory.exists()) {
1810 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1813 // Enable Clear DOM Storage if there is any.
1814 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1816 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1817 if (Build.VERSION.SDK_INT < 26) {
1818 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1819 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1822 // Enable Clear Data if any of the submenu items are enabled.
1823 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1825 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
1826 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1828 // Initialize font size variables.
1829 int fontSize = mainWebView.getSettings().getTextZoom();
1830 String fontSizeTitle;
1831 MenuItem selectedFontSizeMenuItem;
1833 // Prepare the font size title and current size menu item.
1836 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1837 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1841 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1842 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1846 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1847 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1851 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1852 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1856 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1857 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1861 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1862 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1866 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1867 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1871 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1872 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1876 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1877 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1881 // Set the font size title and select the current size menu item.
1882 fontSizeMenuItem.setTitle(fontSizeTitle);
1883 selectedFontSizeMenuItem.setChecked(true);
1885 // Run all the other default commands.
1886 super.onPrepareOptionsMenu(menu);
1888 // Display the menu.
1893 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1894 @SuppressLint("SetJavaScriptEnabled")
1895 // removeAllCookies is deprecated, but it is required for API < 21.
1896 @SuppressWarnings("deprecation")
1897 public boolean onOptionsItemSelected(MenuItem menuItem) {
1898 // Get the selected menu item ID.
1899 int menuItemId = menuItem.getItemId();
1901 // Set the commands that relate to the menu entries.
1902 switch (menuItemId) {
1903 case R.id.toggle_javascript:
1904 // Switch the status of javaScriptEnabled.
1905 javaScriptEnabled = !javaScriptEnabled;
1907 // Apply the new JavaScript status.
1908 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1910 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1911 updatePrivacyIcons(true);
1913 // Display a `Snackbar`.
1914 if (javaScriptEnabled) { // JavaScrip is enabled.
1915 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1916 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1917 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1918 } else { // Privacy mode.
1919 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1922 // Reload the WebView.
1923 mainWebView.reload();
1926 case R.id.add_or_edit_domain:
1927 if (domainSettingsApplied) { // Edit the current domain settings.
1928 // Reapply the domain settings on returning to `MainWebViewActivity`.
1929 reapplyDomainSettingsOnRestart = true;
1930 currentDomainName = "";
1932 // Create an intent to launch the domains activity.
1933 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1935 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
1936 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
1937 domainsIntent.putExtra("closeOnBack", true);
1940 startActivity(domainsIntent);
1941 } else { // Add a new domain.
1942 // Apply the new domain settings on returning to `MainWebViewActivity`.
1943 reapplyDomainSettingsOnRestart = true;
1944 currentDomainName = "";
1946 // Get the current domain
1947 Uri currentUri = Uri.parse(formattedUrlString);
1948 String currentDomain = currentUri.getHost();
1950 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1951 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1953 // Create the domain and store the database ID.
1954 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1956 // Create an intent to launch the domains activity.
1957 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1959 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
1960 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
1961 domainsIntent.putExtra("closeOnBack", true);
1964 startActivity(domainsIntent);
1968 case R.id.toggle_first_party_cookies:
1969 // Switch the status of firstPartyCookiesEnabled.
1970 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1972 // Update the menu checkbox.
1973 menuItem.setChecked(firstPartyCookiesEnabled);
1975 // Apply the new cookie status.
1976 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1978 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1979 updatePrivacyIcons(true);
1981 // Display a `Snackbar`.
1982 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1983 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1984 } else if (javaScriptEnabled) { // JavaScript is still enabled.
1985 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1986 } else { // Privacy mode.
1987 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1990 // Reload the WebView.
1991 mainWebView.reload();
1994 case R.id.toggle_third_party_cookies:
1995 if (Build.VERSION.SDK_INT >= 21) {
1996 // Switch the status of thirdPartyCookiesEnabled.
1997 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1999 // Update the menu checkbox.
2000 menuItem.setChecked(thirdPartyCookiesEnabled);
2002 // Apply the new cookie status.
2003 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2005 // Display a `Snackbar`.
2006 if (thirdPartyCookiesEnabled) {
2007 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2009 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2012 // Reload the WebView.
2013 mainWebView.reload();
2014 } // Else do nothing because SDK < 21.
2017 case R.id.toggle_dom_storage:
2018 // Switch the status of domStorageEnabled.
2019 domStorageEnabled = !domStorageEnabled;
2021 // Update the menu checkbox.
2022 menuItem.setChecked(domStorageEnabled);
2024 // Apply the new DOM Storage status.
2025 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2027 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2028 updatePrivacyIcons(true);
2030 // Display a `Snackbar`.
2031 if (domStorageEnabled) {
2032 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2034 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2037 // Reload the WebView.
2038 mainWebView.reload();
2041 // Form data can be removed once the minimum API >= 26.
2042 case R.id.toggle_save_form_data:
2043 // Switch the status of saveFormDataEnabled.
2044 saveFormDataEnabled = !saveFormDataEnabled;
2046 // Update the menu checkbox.
2047 menuItem.setChecked(saveFormDataEnabled);
2049 // Apply the new form data status.
2050 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2052 // Display a `Snackbar`.
2053 if (saveFormDataEnabled) {
2054 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2056 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2059 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2060 updatePrivacyIcons(true);
2062 // Reload the WebView.
2063 mainWebView.reload();
2066 case R.id.clear_cookies:
2067 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2068 .setAction(R.string.undo, v -> {
2069 // Do nothing because everything will be handled by `onDismissed()` below.
2071 .addCallback(new Snackbar.Callback() {
2073 public void onDismissed(Snackbar snackbar, int event) {
2075 // The user pushed the `Undo` button.
2076 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2080 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2082 // `cookieManager.removeAllCookie()` varies by SDK.
2083 if (Build.VERSION.SDK_INT < 21) {
2084 cookieManager.removeAllCookie();
2086 // `null` indicates no callback.
2087 cookieManager.removeAllCookies(null);
2095 case R.id.clear_dom_storage:
2096 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2097 .setAction(R.string.undo, v -> {
2098 // Do nothing because everything will be handled by `onDismissed()` below.
2100 .addCallback(new Snackbar.Callback() {
2102 public void onDismissed(Snackbar snackbar, int event) {
2104 // The user pushed the `Undo` button.
2105 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2109 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2111 // Delete the DOM Storage.
2112 WebStorage webStorage = WebStorage.getInstance();
2113 webStorage.deleteAllData();
2115 // Manually delete the DOM storage files and directories.
2117 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2118 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2120 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2121 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2122 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2123 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2124 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2125 } catch (IOException e) {
2126 // Do nothing if an error is thrown.
2134 // Form data can be remove once the minimum API >= 26.
2135 case R.id.clear_form_data:
2136 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2137 .setAction(R.string.undo, v -> {
2138 // Do nothing because everything will be handled by `onDismissed()` below.
2140 .addCallback(new Snackbar.Callback() {
2142 public void onDismissed(Snackbar snackbar, int event) {
2144 // The user pushed the `Undo` button.
2145 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2149 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2151 // Delete the form data.
2152 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2153 mainWebViewDatabase.clearFormData();
2160 case R.id.font_size_twenty_five_percent:
2161 mainWebView.getSettings().setTextZoom(25);
2164 case R.id.font_size_fifty_percent:
2165 mainWebView.getSettings().setTextZoom(50);
2168 case R.id.font_size_seventy_five_percent:
2169 mainWebView.getSettings().setTextZoom(75);
2172 case R.id.font_size_one_hundred_percent:
2173 mainWebView.getSettings().setTextZoom(100);
2176 case R.id.font_size_one_hundred_twenty_five_percent:
2177 mainWebView.getSettings().setTextZoom(125);
2180 case R.id.font_size_one_hundred_fifty_percent:
2181 mainWebView.getSettings().setTextZoom(150);
2184 case R.id.font_size_one_hundred_seventy_five_percent:
2185 mainWebView.getSettings().setTextZoom(175);
2188 case R.id.font_size_two_hundred_percent:
2189 mainWebView.getSettings().setTextZoom(200);
2192 case R.id.swipe_to_refresh:
2193 // Toggle swipe to refresh.
2194 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2197 case R.id.display_images:
2198 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2199 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2200 mainWebView.reload();
2201 } else { // Images are not currently loaded automatically.
2202 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2205 // Set `onTheFlyDisplayImagesSet`.
2206 onTheFlyDisplayImagesSet = true;
2209 case R.id.view_source:
2210 // Launch the View Source activity.
2211 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2212 startActivity(viewSourceIntent);
2216 // Toggle the EasyList status.
2217 easyListEnabled = !easyListEnabled;
2219 // Update the menu checkbox.
2220 menuItem.setChecked(easyListEnabled);
2222 // Reload the main WebView.
2223 mainWebView.reload();
2226 case R.id.easyprivacy:
2227 // Toggle the EasyPrivacy status.
2228 easyPrivacyEnabled = !easyPrivacyEnabled;
2230 // Update the menu checkbox.
2231 menuItem.setChecked(easyPrivacyEnabled);
2233 // Reload the main WebView.
2234 mainWebView.reload();
2237 case R.id.fanboys_annoyance_list:
2238 // Toggle Fanboy's Annoyance List status.
2239 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2241 // Update the menu checkbox.
2242 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2244 // Update the staus of Fanboy's Social Blocking List.
2245 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2246 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2248 // Reload the main WebView.
2249 mainWebView.reload();
2252 case R.id.fanboys_social_blocking_list:
2253 // Toggle Fanboy's Social Blocking List status.
2254 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2256 // Update the menu checkbox.
2257 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2259 // Reload the main WebView.
2260 mainWebView.reload();
2263 case R.id.block_all_third_party_requests:
2264 //Toggle the third-party requests blocker status.
2265 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2267 // Update the menu checkbox.
2268 menuItem.setChecked(blockAllThirdPartyRequests);
2270 // Reload the main WebView.
2271 mainWebView.reload();
2275 // Setup the share string.
2276 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2278 // Create the share intent.
2279 Intent shareIntent = new Intent();
2280 shareIntent.setAction(Intent.ACTION_SEND);
2281 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2282 shareIntent.setType("text/plain");
2285 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2288 case R.id.find_on_page:
2289 // Hide the URL app bar.
2290 supportAppBar.setVisibility(View.GONE);
2292 // Show the Find on Page `RelativeLayout`.
2293 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2295 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2296 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2297 findOnPageEditText.postDelayed(() -> {
2298 // Set the focus on `findOnPageEditText`.
2299 findOnPageEditText.requestFocus();
2301 // Display the keyboard. `0` sets no input flags.
2302 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2307 // Get a `PrintManager` instance.
2308 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2310 // Convert `mainWebView` to `printDocumentAdapter`.
2311 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2313 // Remove the lint error below that `printManager` might be `null`.
2314 assert printManager != null;
2316 // Print the document. The print attributes are `null`.
2317 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2320 case R.id.add_to_homescreen:
2321 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2322 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2323 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2325 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2329 mainWebView.reload();
2332 case R.id.ad_consent:
2333 // Display the ad consent dialog.
2334 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2335 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2339 // Don't consume the event.
2340 return super.onOptionsItemSelected(menuItem);
2344 // removeAllCookies is deprecated, but it is required for API < 21.
2345 @SuppressWarnings("deprecation")
2347 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2348 int menuItemId = menuItem.getItemId();
2350 switch (menuItemId) {
2356 if (mainWebView.canGoBack()) {
2357 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2358 formattedUrlString = "";
2360 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2361 navigatingHistory = true;
2363 // Load the previous website in the history.
2364 mainWebView.goBack();
2369 if (mainWebView.canGoForward()) {
2370 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2371 formattedUrlString = "";
2373 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2374 navigatingHistory = true;
2376 // Load the next website in the history.
2377 mainWebView.goForward();
2382 // Get the `WebBackForwardList`.
2383 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2385 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2386 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2387 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2391 // Launch the requests activity.
2392 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2393 startActivity(requestsIntent);
2396 case R.id.downloads:
2397 // Launch the system Download Manager.
2398 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2400 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2401 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2403 startActivity(downloadManagerIntent);
2407 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2408 reapplyDomainSettingsOnRestart = true;
2409 currentDomainName = "";
2411 // Launch the domains activity.
2412 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2413 startActivity(domainsIntent);
2417 // Set the flag to reapply app settings on restart when returning from Settings.
2418 reapplyAppSettingsOnRestart = true;
2420 // Set the flag to reapply the domain settings on restart when returning from Settings.
2421 reapplyDomainSettingsOnRestart = true;
2422 currentDomainName = "";
2424 // Launch the settings activity.
2425 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2426 startActivity(settingsIntent);
2430 // Launch `GuideActivity`.
2431 Intent guideIntent = new Intent(this, GuideActivity.class);
2432 startActivity(guideIntent);
2436 // Launch `AboutActivity`.
2437 Intent aboutIntent = new Intent(this, AboutActivity.class);
2438 startActivity(aboutIntent);
2441 case R.id.clearAndExit:
2442 // Get a handle for `sharedPreferences`. `this` references the current context.
2443 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2445 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2448 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2449 // The command to remove cookies changed slightly in API 21.
2450 if (Build.VERSION.SDK_INT >= 21) {
2451 cookieManager.removeAllCookies(null);
2453 cookieManager.removeAllCookie();
2456 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2458 // We have to use two commands because `Runtime.exec()` does not like `*`.
2459 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2460 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2461 } catch (IOException e) {
2462 // Do nothing if an error is thrown.
2466 // Clear DOM storage.
2467 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2468 // Ask `WebStorage` to clear the DOM storage.
2469 WebStorage webStorage = WebStorage.getInstance();
2470 webStorage.deleteAllData();
2472 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2474 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2475 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2477 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2478 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2479 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2480 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2481 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2482 } catch (IOException e) {
2483 // Do nothing if an error is thrown.
2487 // Clear form data if the API < 26.
2488 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2489 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2490 webViewDatabase.clearFormData();
2492 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2494 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2495 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2496 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2497 } catch (IOException e) {
2498 // Do nothing if an error is thrown.
2503 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2504 // `true` includes disk files.
2505 mainWebView.clearCache(true);
2507 // Manually delete the cache directories.
2509 // Delete the main cache directory.
2510 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2512 // Delete the secondary `Service Worker` cache directory.
2513 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2514 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2515 } catch (IOException e) {
2516 // Do nothing if an error is thrown.
2520 // Clear SSL certificate preferences.
2521 mainWebView.clearSslPreferences();
2523 // Clear the back/forward history.
2524 mainWebView.clearHistory();
2526 // Clear `formattedUrlString`.
2527 formattedUrlString = null;
2529 // Clear `customHeaders`.
2530 customHeaders.clear();
2532 // Detach all views from `mainWebViewRelativeLayout`.
2533 mainWebViewRelativeLayout.removeAllViews();
2535 // Destroy the internal state of `mainWebView`.
2536 mainWebView.destroy();
2538 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2539 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2540 if (clearEverything) {
2542 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2543 } catch (IOException e) {
2544 // Do nothing if an error is thrown.
2548 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2549 if (Build.VERSION.SDK_INT >= 21) {
2550 finishAndRemoveTask();
2555 // Remove the terminated program from RAM. The status code is `0`.
2560 // Close the navigation drawer.
2561 drawerLayout.closeDrawer(GravityCompat.START);
2566 public void onPostCreate(Bundle savedInstanceState) {
2567 super.onPostCreate(savedInstanceState);
2569 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2570 drawerToggle.syncState();
2574 public void onConfigurationChanged(Configuration newConfig) {
2575 super.onConfigurationChanged(newConfig);
2577 // Reload the ad for the free flavor if we are not in full screen mode.
2578 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2579 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2580 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2583 // `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:
2584 // https://code.google.com/p/android/issues/detail?id=20493#c8
2585 // ActivityCompat.invalidateOptionsMenu(this);
2589 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2590 // Store the `HitTestResult`.
2591 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2594 final String imageUrl;
2595 final String linkUrl;
2597 // Get a handle for the `ClipboardManager`.
2598 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2600 // Remove the lint errors below that `clipboardManager` might be `null`.
2601 assert clipboardManager != null;
2603 switch (hitTestResult.getType()) {
2604 // `SRC_ANCHOR_TYPE` is a link.
2605 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2606 // Get the target URL.
2607 linkUrl = hitTestResult.getExtra();
2609 // Set the target URL as the title of the `ContextMenu`.
2610 menu.setHeaderTitle(linkUrl);
2612 // Add a Load URL entry.
2613 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2618 // Add a Copy URL entry.
2619 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2620 // Save the link URL in a `ClipData`.
2621 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2623 // Set the `ClipData` as the clipboard's primary clip.
2624 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2628 // Add a Download URL entry.
2629 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2630 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2631 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2632 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2634 // Store the variables for future use by `onRequestPermissionsResult()`.
2635 downloadUrl = linkUrl;
2636 downloadContentDisposition = "none";
2637 downloadContentLength = -1;
2639 // Show a dialog if the user has previously denied the permission.
2640 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2641 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2642 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2644 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2645 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2646 } else { // Show the permission request directly.
2647 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2648 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2650 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2651 // Get a handle for the download file alert dialog.
2652 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2654 // Show the download file alert dialog.
2655 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2660 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2661 menu.add(R.string.cancel);
2664 case WebView.HitTestResult.EMAIL_TYPE:
2665 // Get the target URL.
2666 linkUrl = hitTestResult.getExtra();
2668 // Set the target URL as the title of the `ContextMenu`.
2669 menu.setHeaderTitle(linkUrl);
2671 // Add a `Write Email` entry.
2672 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2673 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2674 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2676 // Parse the url and set it as the data for the `Intent`.
2677 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2679 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2680 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2683 startActivity(emailIntent);
2687 // Add a `Copy Email Address` entry.
2688 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2689 // Save the email address in a `ClipData`.
2690 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2692 // Set the `ClipData` as the clipboard's primary clip.
2693 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2697 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2698 menu.add(R.string.cancel);
2701 // `IMAGE_TYPE` is an image.
2702 case WebView.HitTestResult.IMAGE_TYPE:
2703 // Get the image URL.
2704 imageUrl = hitTestResult.getExtra();
2706 // Set the image URL as the title of the `ContextMenu`.
2707 menu.setHeaderTitle(imageUrl);
2709 // Add a `View Image` entry.
2710 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2715 // Add a `Download Image` entry.
2716 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2717 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2718 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2719 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2721 // Store the image URL for use by `onRequestPermissionResult()`.
2722 downloadImageUrl = imageUrl;
2724 // Show a dialog if the user has previously denied the permission.
2725 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2726 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2727 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2729 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2730 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2731 } else { // Show the permission request directly.
2732 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2733 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2735 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2736 // Get a handle for the download image alert dialog.
2737 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2739 // Show the download image alert dialog.
2740 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2745 // Add a `Copy URL` entry.
2746 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2747 // Save the image URL in a `ClipData`.
2748 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2750 // Set the `ClipData` as the clipboard's primary clip.
2751 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2755 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2756 menu.add(R.string.cancel);
2760 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2761 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2762 // Get the image URL.
2763 imageUrl = hitTestResult.getExtra();
2765 // Set the image URL as the title of the `ContextMenu`.
2766 menu.setHeaderTitle(imageUrl);
2768 // Add a `View Image` entry.
2769 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2774 // Add a `Download Image` entry.
2775 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2776 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2777 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2778 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2780 // Store the image URL for use by `onRequestPermissionResult()`.
2781 downloadImageUrl = imageUrl;
2783 // Show a dialog if the user has previously denied the permission.
2784 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2785 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2786 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2788 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2789 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2790 } else { // Show the permission request directly.
2791 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2792 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2794 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2795 // Get a handle for the download image alert dialog.
2796 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2798 // Show the download image alert dialog.
2799 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2804 // Add a `Copy URL` entry.
2805 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2806 // Save the image URL in a `ClipData`.
2807 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2809 // Set the `ClipData` as the clipboard's primary clip.
2810 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2814 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2815 menu.add(R.string.cancel);
2821 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2822 // Get the `EditTexts` from the `dialogFragment`.
2823 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2824 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2826 // Extract the strings from the `EditTexts`.
2827 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2828 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2830 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2831 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2832 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2833 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2835 // Display the new bookmark below the current items in the (0 indexed) list.
2836 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2838 // Create the bookmark.
2839 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2841 // Update `bookmarksCursor` with the current contents of this folder.
2842 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2844 // Update the `ListView`.
2845 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2847 // Scroll to the new bookmark.
2848 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2852 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2853 // Get handles for the views in `dialogFragment`.
2854 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2855 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2856 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2858 // Get new folder name string.
2859 String folderNameString = createFolderNameEditText.getText().toString();
2861 // Get the new folder icon `Bitmap`.
2862 Bitmap folderIconBitmap;
2863 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2864 // Get the default folder icon and convert it to a `Bitmap`.
2865 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2866 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2867 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2868 } else { // Use the `WebView` favorite icon.
2869 folderIconBitmap = favoriteIconBitmap;
2872 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2873 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2874 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2875 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2877 // Move all the bookmarks down one in the display order.
2878 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2879 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2880 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2883 // Create the folder, which will be placed at the top of the `ListView`.
2884 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2886 // Update `bookmarksCursor` with the current contents of this folder.
2887 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2889 // Update the `ListView`.
2890 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2892 // Scroll to the new folder.
2893 bookmarksListView.setSelection(0);
2897 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2898 // Get the shortcut name.
2899 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2900 String shortcutNameString = shortcutNameEditText.getText().toString();
2902 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2903 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2905 // Setup the shortcut intent.
2906 Intent shortcutIntent = new Intent();
2907 shortcutIntent.setAction(Intent.ACTION_VIEW);
2908 shortcutIntent.setData(Uri.parse(formattedUrlString));
2910 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2911 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2913 // Add the required fields to the shortcut info builder.
2914 shortcutInfoBuilder.setIcon(favoriteIcon);
2915 shortcutInfoBuilder.setIntent(shortcutIntent);
2916 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2918 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2919 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2923 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2924 switch (downloadType) {
2925 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2926 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2927 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2930 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2931 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2932 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2938 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
2939 switch (requestCode) {
2940 case DOWNLOAD_FILE_REQUEST_CODE:
2941 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2942 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2944 // On API 23, displaying the fragment must be delayed or the app will crash.
2945 if (Build.VERSION.SDK_INT == 23) {
2946 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2948 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2951 // Reset the download variables.
2953 downloadContentDisposition = "";
2954 downloadContentLength = 0;
2957 case DOWNLOAD_IMAGE_REQUEST_CODE:
2958 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2959 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2961 // On API 23, displaying the fragment must be delayed or the app will crash.
2962 if (Build.VERSION.SDK_INT == 23) {
2963 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2965 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2968 // Reset the image URL variable.
2969 downloadImageUrl = "";
2975 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2976 // Download the image if it has an HTTP or HTTPS URI.
2977 if (imageUrl.startsWith("http")) {
2978 // Get a handle for the system `DOWNLOAD_SERVICE`.
2979 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2981 // Parse `imageUrl`.
2982 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2984 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2985 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2986 if (firstPartyCookiesEnabled) {
2987 // Get the cookies for `imageUrl`.
2988 String cookies = cookieManager.getCookie(imageUrl);
2990 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2991 downloadRequest.addRequestHeader("Cookie", cookies);
2994 // Get the file name from the dialog fragment.
2995 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2996 String imageName = downloadImageNameEditText.getText().toString();
2998 // Specify the download location.
2999 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3000 // Download to the public download directory.
3001 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3002 } else { // External write permission denied.
3003 // Download to the app's external download directory.
3004 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3007 // Allow `MediaScanner` to index the download if it is a media file.
3008 downloadRequest.allowScanningByMediaScanner();
3010 // Add the URL as the description for the download.
3011 downloadRequest.setDescription(imageUrl);
3013 // Show the download notification after the download is completed.
3014 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3016 // Remove the lint warning below that `downloadManager` might be `null`.
3017 assert downloadManager != null;
3019 // Initiate the download.
3020 downloadManager.enqueue(downloadRequest);
3021 } else { // The image is not an HTTP or HTTPS URI.
3022 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3027 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3028 // Download the file if it has an HTTP or HTTPS URI.
3029 if (downloadUrl.startsWith("http")) {
3030 // Get a handle for the system `DOWNLOAD_SERVICE`.
3031 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3033 // Parse `downloadUrl`.
3034 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3036 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3037 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3038 if (firstPartyCookiesEnabled) {
3039 // Get the cookies for `downloadUrl`.
3040 String cookies = cookieManager.getCookie(downloadUrl);
3042 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3043 downloadRequest.addRequestHeader("Cookie", cookies);
3046 // Get the file name from the dialog fragment.
3047 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3048 String fileName = downloadFileNameEditText.getText().toString();
3050 // Specify the download location.
3051 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3052 // Download to the public download directory.
3053 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3054 } else { // External write permission denied.
3055 // Download to the app's external download directory.
3056 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3059 // Allow `MediaScanner` to index the download if it is a media file.
3060 downloadRequest.allowScanningByMediaScanner();
3062 // Add the URL as the description for the download.
3063 downloadRequest.setDescription(downloadUrl);
3065 // Show the download notification after the download is completed.
3066 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3068 // Remove the lint warning below that `downloadManager` might be `null`.
3069 assert downloadManager != null;
3071 // Initiate the download.
3072 downloadManager.enqueue(downloadRequest);
3073 } else { // The download is not an HTTP or HTTPS URI.
3074 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3079 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3080 // Get handles for the views from `dialogFragment`.
3081 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3082 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3083 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3085 // Store the bookmark strings.
3086 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3087 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3089 // Update the bookmark.
3090 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3091 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3092 } else { // Update the bookmark using the `WebView` favorite icon.
3093 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3094 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3095 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3096 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3098 // Update the bookmark and the favorite icon.
3099 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3102 // Update `bookmarksCursor` with the current contents of this folder.
3103 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3105 // Update the `ListView`.
3106 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3110 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3111 // Get handles for the views from `dialogFragment`.
3112 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3113 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3114 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3115 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3117 // Get the new folder name.
3118 String newFolderNameString = editFolderNameEditText.getText().toString();
3120 // Check if the favorite icon has changed.
3121 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3122 // Update the name in the database.
3123 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3124 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3125 // Get the new folder icon `Bitmap`.
3126 Bitmap folderIconBitmap;
3127 if (defaultFolderIconRadioButton.isChecked()) {
3128 // Get the default folder icon and convert it to a `Bitmap`.
3129 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3130 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3131 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3132 } else { // Use the `WebView` favorite icon.
3133 folderIconBitmap = favoriteIconBitmap;
3136 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3137 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3138 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3139 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3141 // Update the folder icon in the database.
3142 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3143 } else { // The folder icon and the name have changed.
3144 // Get the new folder icon `Bitmap`.
3145 Bitmap folderIconBitmap;
3146 if (defaultFolderIconRadioButton.isChecked()) {
3147 // Get the default folder icon and convert it to a `Bitmap`.
3148 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3149 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3150 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3151 } else { // Use the `WebView` favorite icon.
3152 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3155 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3156 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3157 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3158 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3160 // Update the folder name and icon in the database.
3161 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3164 // Update `bookmarksCursor` with the current contents of this folder.
3165 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3167 // Update the `ListView`.
3168 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3172 public void onHttpAuthenticationCancel() {
3173 // Cancel the `HttpAuthHandler`.
3174 httpAuthHandler.cancel();
3178 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3179 // Get handles for the `EditTexts`.
3180 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3181 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3183 // Proceed with the HTTP authentication.
3184 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3187 public void viewSslCertificate(View view) {
3188 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3189 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3190 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3194 public void onSslErrorCancel() {
3195 sslErrorHandler.cancel();
3199 public void onSslErrorProceed() {
3200 sslErrorHandler.proceed();
3204 public void onSslMismatchBack() {
3205 if (mainWebView.canGoBack()) { // There is a back page in the history.
3206 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3207 formattedUrlString = "";
3209 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3210 navigatingHistory = true;
3213 mainWebView.goBack();
3214 } else { // There are no pages to go back to.
3215 // Load a blank page
3221 public void onSslMismatchProceed() {
3222 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3223 ignorePinnedSslCertificate = true;
3227 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3228 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3229 formattedUrlString = "";
3231 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3232 navigatingHistory = true;
3234 // Load the history entry.
3235 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3239 public void onClearHistory() {
3240 // Clear the history.
3241 mainWebView.clearHistory();
3244 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3246 public void onBackPressed() {
3247 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3248 // Close the navigation drawer.
3249 drawerLayout.closeDrawer(GravityCompat.START);
3250 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3251 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3252 // close the bookmarks drawer.
3253 drawerLayout.closeDrawer(GravityCompat.END);
3254 } else { // A subfolder is displayed.
3255 // Place the former parent folder in `currentFolder`.
3256 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3258 // Load the new folder.
3259 loadBookmarksFolder();
3262 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3263 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3264 formattedUrlString = "";
3266 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3267 navigatingHistory = true;
3270 mainWebView.goBack();
3271 } else { // There isn't anything to do in Privacy Browser.
3272 // Pass `onBackPressed()` to the system.
3273 super.onBackPressed();
3277 // 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.
3279 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3280 // File uploads only work on API >= 21.
3281 if (Build.VERSION.SDK_INT >= 21) {
3282 // Pass the file to the WebView.
3283 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3287 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3288 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3289 String unformattedUrlString = urlTextBox.getText().toString().trim();
3291 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3292 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3293 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3294 if (!unformattedUrlString.startsWith("http")) {
3295 unformattedUrlString = "http://" + unformattedUrlString;
3298 // Initialize `unformattedUrl`.
3299 URL unformattedUrl = null;
3301 // 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.
3303 unformattedUrl = new URL(unformattedUrlString);
3304 } catch (MalformedURLException e) {
3305 e.printStackTrace();
3308 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3309 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3310 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3311 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3312 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3313 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3316 Uri.Builder formattedUri = new Uri.Builder();
3317 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3319 // Decode `formattedUri` as a `String` in `UTF-8`.
3320 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3321 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3322 // Load a blank string.
3323 formattedUrlString = "";
3324 } else { // Search for the contents of the URL box.
3325 // Sanitize the search input and convert it to a search.
3326 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3328 // Add the base search URL.
3329 formattedUrlString = searchURL + encodedUrlString;
3332 // 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.
3333 urlTextBox.clearFocus();
3336 loadUrl(formattedUrlString);
3339 private void loadUrl(String url) {// Apply any custom domain settings.
3340 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3341 formattedUrlString = url;
3343 // Apply the domain settings.
3344 applyDomainSettings(url, true, false);
3346 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3347 urlIsLoading = true;
3350 mainWebView.loadUrl(url, customHeaders);
3353 public void findPreviousOnPage(View view) {
3354 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3355 mainWebView.findNext(false);
3358 public void findNextOnPage(View view) {
3359 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3360 mainWebView.findNext(true);
3363 public void closeFindOnPage(View view) {
3364 // Delete the contents of `find_on_page_edittext`.
3365 findOnPageEditText.setText(null);
3367 // Clear the highlighted phrases.
3368 mainWebView.clearMatches();
3370 // Hide the Find on Page `RelativeLayout`.
3371 findOnPageLinearLayout.setVisibility(View.GONE);
3373 // Show the URL app bar.
3374 supportAppBar.setVisibility(View.VISIBLE);
3376 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3377 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3380 private void applyAppSettings() {
3381 // Get a handle for the shared preferences.
3382 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3384 // Store the values from the shared preferences in variables.
3385 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3386 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3387 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3388 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3389 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3390 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3391 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3392 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3393 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3394 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3395 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3396 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3397 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3399 // Set the homepage, search, and proxy options.
3400 if (proxyThroughOrbot) { // Set the Tor options.
3401 // Set `torHomepageString` as `homepage`.
3402 homepage = torHomepageString;
3404 // If formattedUrlString is null assign the homepage to it.
3405 if (formattedUrlString == null) {
3406 formattedUrlString = homepage;
3409 // Set the search URL.
3410 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3411 searchURL = torSearchCustomURLString;
3412 } else { // Use the string from the pre-built list.
3413 searchURL = torSearchString;
3416 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3417 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3419 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3421 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3423 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3426 // Display a message to the user if we are waiting on Orbot.
3427 if (!orbotStatus.equals("ON")) {
3428 // Set `waitingForOrbot`.
3429 waitingForOrbot = true;
3431 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3432 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3434 } else { // Set the non-Tor options.
3435 // Set `homepageString` as `homepage`.
3436 homepage = homepageString;
3438 // If formattedUrlString is null assign the homepage to it.
3439 if (formattedUrlString == null) {
3440 formattedUrlString = homepage;
3443 // Set the search URL.
3444 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3445 searchURL = searchCustomURLString;
3446 } else { // Use the string from the pre-built list.
3447 searchURL = searchString;
3450 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3451 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3453 // Set the default `appBar` background. `this` refers to the context.
3455 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3457 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3460 // Reset `waitingForOrbot.
3461 waitingForOrbot = false;
3464 // Set Do Not Track status.
3465 if (doNotTrackEnabled) {
3466 customHeaders.put("DNT", "1");
3468 customHeaders.remove("DNT");
3471 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3472 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3473 if (hideSystemBarsOnFullscreen) { // Hide everything.
3474 // Remove the translucent navigation setting if it is currently flagged.
3475 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3477 // Remove the translucent status bar overlay.
3478 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3480 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3481 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3483 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3484 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3485 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3487 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3488 } else { // Hide everything except the status and navigation bars.
3489 // Add the translucent status flag if it is unset.
3490 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3492 if (translucentNavigationBarOnFullscreen) {
3493 // Set the navigation bar to be translucent.
3494 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3496 // Set the navigation bar to be black.
3497 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3500 } else { // Switch to normal viewing mode.
3501 // Reset `inFullScreenBrowsingMode` to `false`.
3502 inFullScreenBrowsingMode = false;
3504 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3505 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3509 // Show the `BannerAd` in the free flavor.
3510 if (BuildConfig.FLAVOR.contentEquals("free")) {
3511 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3512 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3515 // Remove the translucent navigation bar flag if it is set.
3516 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3518 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3519 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3521 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3522 rootCoordinatorLayout.setSystemUiVisibility(0);
3524 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3525 rootCoordinatorLayout.setFitsSystemWindows(true);
3529 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3530 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3531 @SuppressWarnings("deprecation")
3532 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3533 // Parse the URL into a URI.
3534 Uri uri = Uri.parse(url);
3536 // Extract the domain from `uri`.
3537 String hostName = uri.getHost();
3539 // Initialize `loadingNewDomainName`.
3540 boolean loadingNewDomainName;
3542 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3543 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3544 //noinspection SimplifiableIfStatement
3545 if ((hostName == null) || (currentDomainName == null)) {
3546 loadingNewDomainName = true;
3547 } else { // Determine if `hostName` equals `currentDomainName`.
3548 loadingNewDomainName = !hostName.equals(currentDomainName);
3551 // Strings don't like to be null.
3552 if (hostName == null) {
3556 // 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.
3557 if (loadingNewDomainName) {
3558 // Set the new `hostname` as the `currentDomainName`.
3559 currentDomainName = hostName;
3561 // Reset `ignorePinnedSslCertificate`.
3562 ignorePinnedSslCertificate = false;
3564 // Reset the favorite icon if specified.
3565 if (resetFavoriteIcon) {
3566 favoriteIconBitmap = favoriteIconDefaultBitmap;
3567 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3570 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3571 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3572 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3574 // Get a full cursor from `domainsDatabaseHelper`.
3575 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3577 // Initialize `domainSettingsSet`.
3578 Set<String> domainSettingsSet = new HashSet<>();
3580 // Get the domain name column index.
3581 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3583 // Populate `domainSettingsSet`.
3584 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3585 // Move `domainsCursor` to the current row.
3586 domainNameCursor.moveToPosition(i);
3588 // Store the domain name in `domainSettingsSet`.
3589 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3592 // Close `domainNameCursor.
3593 domainNameCursor.close();
3595 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3596 domainSettingsApplied = false;
3597 String domainNameInDatabase = null;
3599 // Check the hostname.
3600 if (domainSettingsSet.contains(hostName)) {
3601 domainSettingsApplied = true;
3602 domainNameInDatabase = hostName;
3605 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3606 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3607 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3608 // Apply the domain settings.
3609 domainSettingsApplied = true;
3611 // Store the applied domain names as it appears in the database.
3612 domainNameInDatabase = "*." + hostName;
3615 // Strip out the lowest subdomain of of the host name.
3616 hostName = hostName.substring(hostName.indexOf(".") + 1);
3620 // Get a handle for the shared preference.
3621 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3623 // Store the general preference information.
3624 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3625 String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3626 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3627 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3628 nightMode = sharedPreferences.getBoolean("night_mode", false);
3630 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3631 // Get a cursor for the current host and move it to the first position.
3632 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3633 currentHostDomainSettingsCursor.moveToFirst();
3635 // Get the settings from the cursor.
3636 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3637 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3638 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3639 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3640 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3641 // Form data can be removed once the minimum API >= 26.
3642 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3643 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3644 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3645 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3646 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3647 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3648 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3649 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3650 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3651 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3652 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3653 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3654 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3655 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3656 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3657 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3658 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3659 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3661 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3662 switch (nightModeInt) {
3663 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3667 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3672 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3674 javaScriptEnabled = true;
3677 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3678 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3679 pinnedDomainSslStartDate = null;
3681 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3684 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3685 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3686 pinnedDomainSslEndDate = null;
3688 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3691 // Close `currentHostDomainSettingsCursor`.
3692 currentHostDomainSettingsCursor.close();
3694 // Apply the domain settings.
3695 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3696 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3697 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3699 // Apply the form data setting if the API < 26.
3700 if (Build.VERSION.SDK_INT < 26) {
3701 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3704 // Apply the font size.
3705 if (fontSize == 0) { // Apply the default font size.
3706 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3707 } else { // Apply the specified font size.
3708 mainWebView.getSettings().setTextZoom(fontSize);
3711 // Set third-party cookies status if API >= 21.
3712 if (Build.VERSION.SDK_INT >= 21) {
3713 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3716 // 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.
3717 // <https://redmine.stoutner.com/issues/160>
3718 if (!urlIsLoading) {
3719 // Set the user agent.
3720 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3721 // Get the array position of the default user agent name.
3722 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3724 // Set the user agent according to the system default.
3725 switch (defaultUserAgentArrayPosition) {
3726 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3727 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3728 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3731 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3732 // Set the user agent to `""`, which uses the default value.
3733 mainWebView.getSettings().setUserAgentString("");
3736 case SETTINGS_CUSTOM_USER_AGENT:
3737 // Set the custom user agent.
3738 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3742 // Get the user agent string from the user agent data array
3743 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3745 } else { // Set the user agent according to the stored name.
3746 // Get the array position of the user agent name.
3747 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3749 switch (userAgentArrayPosition) {
3750 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3751 mainWebView.getSettings().setUserAgentString(userAgentName);
3754 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3755 // Set the user agent to `""`, which uses the default value.
3756 mainWebView.getSettings().setUserAgentString("");
3760 // Get the user agent string from the user agent data array.
3761 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3765 // Set swipe to refresh.
3766 switch (swipeToRefreshInt) {
3767 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3768 // Set swipe to refresh according to the default.
3769 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3772 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3773 // Enable swipe to refresh.
3774 swipeRefreshLayout.setEnabled(true);
3777 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3778 // Disable swipe to refresh.
3779 swipeRefreshLayout.setEnabled(false);
3782 // Store the applied user agent string, which is used in the View Source activity.
3783 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3786 // 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.
3788 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3790 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3792 } else { // The new URL does not have custom domain settings. Load the defaults.
3793 // Store the values from `sharedPreferences` in variables.
3794 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3795 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3796 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3797 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3798 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false); // Form data can be removed once the minimum API >= 26.
3799 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3800 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3801 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3802 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3803 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
3805 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3807 javaScriptEnabled = true;
3810 // Apply the default settings.
3811 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3812 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3813 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3814 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3815 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3817 // Apply the form data setting if the API < 26.
3818 if (Build.VERSION.SDK_INT < 26) {
3819 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3822 // Reset the pinned SSL certificate information.
3823 domainSettingsDatabaseId = -1;
3824 pinnedDomainSslCertificate = false;
3825 pinnedDomainSslIssuedToCNameString = "";
3826 pinnedDomainSslIssuedToONameString = "";
3827 pinnedDomainSslIssuedToUNameString = "";
3828 pinnedDomainSslIssuedByCNameString = "";
3829 pinnedDomainSslIssuedByONameString = "";
3830 pinnedDomainSslIssuedByUNameString = "";
3831 pinnedDomainSslStartDate = null;
3832 pinnedDomainSslEndDate = null;
3834 // Set third-party cookies status if API >= 21.
3835 if (Build.VERSION.SDK_INT >= 21) {
3836 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3839 // 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.
3840 // <https://redmine.stoutner.com/issues/160>
3841 if (!urlIsLoading) {
3842 // Get the array position of the user agent name.
3843 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3845 // Set the user agent.
3846 switch (userAgentArrayPosition) {
3847 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3848 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3849 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3852 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3853 // Set the user agent to `""`, which uses the default value.
3854 mainWebView.getSettings().setUserAgentString("");
3857 case SETTINGS_CUSTOM_USER_AGENT:
3858 // Set the custom user agent.
3859 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3863 // Get the user agent string from the user agent data array
3864 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3867 // Store the applied user agent string, which is used in the View Source activity.
3868 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3871 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3872 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3875 // Close `domainsDatabaseHelper`.
3876 domainsDatabaseHelper.close();
3878 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3879 onTheFlyDisplayImagesSet = false;
3880 setDisplayWebpageImages();
3882 // Update the privacy icons, but only if `mainMenu` has already been populated.
3883 if (mainMenu != null) {
3884 updatePrivacyIcons(true);
3888 // Reload the website if returning from the Domains activity.
3889 if (reloadWebsite) {
3890 mainWebView.reload();
3894 private void setDisplayWebpageImages() {
3895 if (!onTheFlyDisplayImagesSet) {
3896 if (domainSettingsApplied) { // Custom domain settings are applied.
3897 switch (displayWebpageImagesInt) {
3898 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3899 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3902 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3903 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3906 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3907 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3910 } else { // Default settings are applied.
3911 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3916 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3917 // Get handles for the menu items.
3918 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3919 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3920 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3921 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
3923 // Update the privacy icon.
3924 if (javaScriptEnabled) { // JavaScript is enabled.
3925 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3926 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3927 privacyMenuItem.setIcon(R.drawable.warning);
3928 } else { // All the dangerous features are disabled.
3929 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3932 // Update the first-party cookies icon.
3933 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3934 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3935 } else { // First-party cookies are disabled.
3937 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3939 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3943 // Update the DOM storage icon.
3944 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3945 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3946 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3948 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3950 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3952 } else { // JavaScript is disabled, so DOM storage is ghosted.
3954 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3956 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3960 // Update the refresh icon.
3962 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3964 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3967 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3968 if (runInvalidateOptionsMenu) {
3969 invalidateOptionsMenu();
3973 private void highlightUrlText() {
3974 String urlString = urlTextBox.getText().toString();
3976 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3977 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3978 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3979 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3982 // Get the index of the `/` immediately after the domain name.
3983 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3985 // De-emphasize the text after the domain name.
3986 if (endOfDomainName > 0) {
3987 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3991 private void loadBookmarksFolder() {
3992 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
3993 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3995 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3996 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3998 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3999 // Inflate the individual item layout. `false` does not attach it to the root.
4000 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4004 public void bindView(View view, Context context, Cursor cursor) {
4005 // Get handles for the views.
4006 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4007 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4009 // Get the favorite icon byte array from the cursor.
4010 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4012 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4013 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4015 // Display the bitmap in `bookmarkFavoriteIcon`.
4016 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4018 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4019 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4020 bookmarkNameTextView.setText(bookmarkNameString);
4022 // Make the font bold for folders.
4023 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4024 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4025 } else { // Reset the font to default for normal bookmarks.
4026 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4031 // Populate the `ListView` with the adapter.
4032 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4034 // Set the bookmarks drawer title.
4035 if (currentBookmarksFolder.isEmpty()) {
4036 bookmarksTitleTextView.setText(R.string.bookmarks);
4038 bookmarksTitleTextView.setText(currentBookmarksFolder);