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()` and `onResume()`.
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()`, `onResume()`, 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 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1193 formattedUrlString = "";
1195 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1196 applyDomainSettings(url, true, false);
1198 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1200 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1201 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1202 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1204 // Parse the url and set it as the data for the intent.
1205 emailIntent.setData(Uri.parse(url));
1207 // Open the email program in a new task instead of as part of Privacy Browser.
1208 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1211 startActivity(emailIntent);
1213 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1215 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1216 // Open the dialer and load the phone number, but wait for the user to place the call.
1217 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1219 // Add the phone number to the intent.
1220 dialIntent.setData(Uri.parse(url));
1222 // Open the dialer in a new task instead of as part of Privacy Browser.
1223 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1226 startActivity(dialIntent);
1228 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1230 } else { // Load a system chooser to select an app that can handle the URL.
1231 // Open an app that can handle the URL.
1232 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1234 // Add the URL to the intent.
1235 genericIntent.setData(Uri.parse(url));
1237 // List all apps that can handle the URL instead of just opening the first one.
1238 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1240 // Open the app in a new task instead of as part of Privacy Browser.
1241 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1243 // Start the app or display a snackbar if no app is available to handle the URL.
1245 startActivity(genericIntent);
1246 } catch (ActivityNotFoundException exception) {
1247 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1250 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1255 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1256 @SuppressWarnings("deprecation")
1258 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1259 // Create an empty web resource response to be used if the resource request is blocked.
1260 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1262 // Reset `whiteListResultStringArray`.
1263 whiteListResultStringArray = null;
1265 // Initialize the third party request tracker.
1266 boolean isThirdPartyRequest = false;
1268 // Initialize the current domain string.
1269 String currentDomain = "";
1271 // Nobody is happy when comparing null strings.
1272 if (!(formattedUrlString == null) && !(url == null)) {
1273 // Get the domain strings to URIs.
1274 Uri currentDomainUri = Uri.parse(formattedUrlString);
1275 Uri requestDomainUri = Uri.parse(url);
1277 // Get the domain host names.
1278 String currentBaseDomain = currentDomainUri.getHost();
1279 String requestBaseDomain = requestDomainUri.getHost();
1281 // Update the current domain variable.
1282 currentDomain = currentBaseDomain;
1284 // Only compare the current base domain and the request base domain if neither is null.
1285 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1286 // Determine the current base domain.
1287 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1288 // Remove the first subdomain.
1289 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1292 // Determine the request base domain.
1293 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1294 // Remove the first subdomain.
1295 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1298 // Update the third party request tracker.
1299 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1303 // Block third-party requests if enabled.
1304 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1305 // Add the request to the log.
1306 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1308 // Return an empty web resource response.
1309 return emptyWebResourceResponse;
1312 // Check EasyList if it is enabled.
1313 if (easyListEnabled) {
1314 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1315 // The resource request was blocked. Return an empty web resource response.
1316 return emptyWebResourceResponse;
1320 // Check EasyPrivacy if it is enabled.
1321 if (easyPrivacyEnabled) {
1322 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1323 // The resource request was blocked. Return an empty web resource response.
1324 return emptyWebResourceResponse;
1328 // Check Fanboy’s Annoyance List if it is enabled.
1329 if (fanboysAnnoyanceListEnabled) {
1330 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1331 // The resource request was blocked. Return an empty web resource response.
1332 return emptyWebResourceResponse;
1334 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1335 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1336 // The resource request was blocked. Return an empty web resource response.
1337 return emptyWebResourceResponse;
1341 // Add the request to the log because it hasn't been processed by any of the previous checks.
1342 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1343 resourceRequests.add(whiteListResultStringArray);
1344 } else { // The request didn't match any blocklist entry. Log it as a defult request.
1345 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1348 // The resource request has not been blocked. `return null` loads the requested resource.
1352 // Handle HTTP authentication requests.
1354 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1355 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1356 httpAuthHandler = handler;
1358 // Display the HTTP authentication dialog.
1359 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1360 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1363 // Update the URL in urlTextBox when the page starts to load.
1365 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1366 // Reset the list of resource requests.
1367 resourceRequests.clear();
1369 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1371 mainWebView.setVisibility(View.INVISIBLE);
1374 // Hide the keyboard. `0` indicates no additional flags.
1375 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1377 // Check to see if Privacy Browser is waiting on Orbot.
1378 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1379 // 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.
1380 formattedUrlString = url;
1382 // Display the formatted URL text.
1383 urlTextBox.setText(formattedUrlString);
1385 // Apply text highlighting to `urlTextBox`.
1388 // Apply any custom domain settings if the URL was loaded by navigating history.
1389 if (navigatingHistory) {
1390 // Reset `navigatingHistory`.
1391 navigatingHistory = false;
1393 // Apply the domain settings.
1394 applyDomainSettings(url, true, false);
1397 // 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.
1398 urlIsLoading = true;
1402 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1404 public void onPageFinished(WebView view, String url) {
1405 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1406 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1407 cookieManager.flush();
1410 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1411 urlIsLoading = false;
1413 // Clear the cache and history if Incognito Mode is enabled.
1414 if (incognitoModeEnabled) {
1415 // Clear the cache. `true` includes disk files.
1416 mainWebView.clearCache(true);
1418 // Clear the back/forward history.
1419 mainWebView.clearHistory();
1421 // Manually delete cache folders.
1423 // Delete the main cache directory.
1424 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1426 // Delete the secondary `Service Worker` cache directory.
1427 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1428 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1429 } catch (IOException e) {
1430 // Do nothing if an error is thrown.
1434 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1435 if (!waitingForOrbot) {
1436 // Check to see if `WebView` has set `url` to be `about:blank`.
1437 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1438 // Set `formattedUrlString` to `""`.
1439 formattedUrlString = "";
1441 urlTextBox.setText(formattedUrlString);
1443 // Request focus for `urlTextBox`.
1444 urlTextBox.requestFocus();
1446 // Display the keyboard.
1447 inputMethodManager.showSoftInput(urlTextBox, 0);
1449 // Apply the domain settings. This clears any settings from the previous domain.
1450 applyDomainSettings(formattedUrlString, true, false);
1451 } else { // `WebView` has loaded a webpage.
1452 // Set `formattedUrlString`.
1453 formattedUrlString = url;
1455 // Only update `urlTextBox` if the user is not typing in it.
1456 if (!urlTextBox.hasFocus()) {
1457 // Display the formatted URL text.
1458 urlTextBox.setText(formattedUrlString);
1460 // Apply text highlighting to `urlTextBox`.
1465 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1466 sslCertificate = mainWebView.getCertificate();
1468 // 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.
1469 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1470 // Initialize the current SSL certificate variables.
1471 String currentWebsiteIssuedToCName = "";
1472 String currentWebsiteIssuedToOName = "";
1473 String currentWebsiteIssuedToUName = "";
1474 String currentWebsiteIssuedByCName = "";
1475 String currentWebsiteIssuedByOName = "";
1476 String currentWebsiteIssuedByUName = "";
1477 Date currentWebsiteSslStartDate = null;
1478 Date currentWebsiteSslEndDate = null;
1481 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1482 if (sslCertificate != null) {
1483 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1484 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1485 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1486 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1487 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1488 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1489 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1490 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1493 // 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`.
1494 String currentWebsiteSslStartDateString = "";
1495 String currentWebsiteSslEndDateString = "";
1496 String pinnedDomainSslStartDateString = "";
1497 String pinnedDomainSslEndDateString = "";
1499 // Convert the `Dates` to `Strings` if they are not `null`.
1500 if (currentWebsiteSslStartDate != null) {
1501 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1504 if (currentWebsiteSslEndDate != null) {
1505 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1508 if (pinnedDomainSslStartDate != null) {
1509 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1512 if (pinnedDomainSslEndDate != null) {
1513 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1516 // Check to see if the pinned SSL certificate matches the current website certificate.
1517 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1518 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1519 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1520 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1521 // The pinned SSL certificate doesn't match the current domain certificate.
1522 //Display the pinned SSL certificate mismatch `AlertDialog`.
1523 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1524 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1530 // Handle SSL Certificate errors.
1532 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1533 // Get the current website SSL certificate.
1534 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1536 // Extract the individual pieces of information from the current website SSL certificate.
1537 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1538 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1539 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1540 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1541 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1542 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1543 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1544 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1546 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1547 if (pinnedDomainSslCertificate &&
1548 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1549 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1550 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1551 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1552 // An SSL certificate is pinned and matches the current domain certificate.
1553 // Proceed to the website without displaying an error.
1555 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1556 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1557 sslErrorHandler = handler;
1559 // Display the SSL error `AlertDialog`.
1560 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1561 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1566 // Load the website if not waiting for Orbot to connect.
1567 if (!waitingForOrbot) {
1568 loadUrl(formattedUrlString);
1573 protected void onNewIntent(Intent intent) {
1574 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1577 // Check to see if the intent contains a new URL.
1578 if (intent.getData() != null) {
1579 // Get the intent data.
1580 final Uri intentUriData = intent.getData();
1582 // Load the website.
1583 loadUrl(intentUriData.toString());
1585 // Close the navigation drawer if it is open.
1586 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1587 drawerLayout.closeDrawer(GravityCompat.START);
1590 // Close the bookmarks drawer if it is open.
1591 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1592 drawerLayout.closeDrawer(GravityCompat.END);
1595 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1596 mainWebView.requestFocus();
1601 public void onRestart() {
1602 // Run the default commands.
1605 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1606 if (proxyThroughOrbot) {
1607 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1608 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1610 // Send the intent to the Orbot package.
1611 orbotIntent.setPackage("org.torproject.android");
1614 sendBroadcast(orbotIntent);
1617 // Apply the app settings if returning from the Settings activity..
1618 if (reapplyAppSettingsOnRestart) {
1619 // Apply the app settings.
1622 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1623 if (reloadOnRestart) {
1624 // Reload `mainWebView`.
1625 mainWebView.reload();
1627 // Reset `reloadOnRestartBoolean`.
1628 reloadOnRestart = false;
1631 // Reset the return from settings flag.
1632 reapplyAppSettingsOnRestart = false;
1635 // Apply the domain settings if returning from the Domains activity.
1636 if (reapplyDomainSettingsOnRestart) {
1637 // Reapply the domain settings.
1638 applyDomainSettings(formattedUrlString, false, true);
1640 // Reset `reapplyDomainSettingsOnRestart`.
1641 reapplyDomainSettingsOnRestart = false;
1644 // Load the URL on restart to apply changes to night mode.
1645 if (loadUrlOnRestart) {
1646 // Load the current `formattedUrlString`.
1647 loadUrl(formattedUrlString);
1649 // Reset `loadUrlOnRestart.
1650 loadUrlOnRestart = false;
1653 // Update the bookmarks drawer if returning from the Bookmarks activity.
1654 if (restartFromBookmarksActivity) {
1655 // Close the bookmarks drawer.
1656 drawerLayout.closeDrawer(GravityCompat.END);
1658 // Reload the bookmarks drawer.
1659 loadBookmarksFolder();
1661 // Reset `restartFromBookmarksActivity`.
1662 restartFromBookmarksActivity = false;
1665 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1666 updatePrivacyIcons(true);
1669 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1671 public void onResume() {
1672 // Run the default commands.
1675 // Resume JavaScript (if enabled).
1676 mainWebView.resumeTimers();
1678 // Resume `mainWebView`.
1679 mainWebView.onResume();
1681 // Resume the adView for the free flavor.
1682 if (BuildConfig.FLAVOR.contentEquals("free")) {
1683 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1684 AdHelper.resumeAd(findViewById(R.id.adview));
1687 // Display a message to the user if waiting for Orbot.
1688 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1689 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1690 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1695 public void onPause() {
1696 // Pause `mainWebView`.
1697 mainWebView.onPause();
1699 // Stop all JavaScript.
1700 mainWebView.pauseTimers();
1702 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1703 if (BuildConfig.FLAVOR.contentEquals("free")) {
1704 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1705 AdHelper.pauseAd(findViewById(R.id.adview));
1712 public boolean onCreateOptionsMenu(Menu menu) {
1713 // Inflate the menu; this adds items to the action bar if it is present.
1714 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1716 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1719 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1720 updatePrivacyIcons(false);
1722 // Get handles for the menu items.
1723 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1724 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1725 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1726 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1727 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1728 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1729 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1731 // Only display third-party cookies if API >= 21
1732 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1734 // Only display the form data menu items if the API < 26.
1735 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1736 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1738 // Only show Ad Consent if this is the free flavor.
1739 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1741 // Get the shared preference values. `this` references the current context.
1742 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1744 // 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.
1745 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1746 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1747 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1748 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1749 } else { //Do not display the additional icons.
1750 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1751 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1752 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1759 public boolean onPrepareOptionsMenu(Menu menu) {
1760 // Get handles for the menu items.
1761 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1762 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1763 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1764 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1765 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1766 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1767 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1768 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1769 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1770 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1771 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1772 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1773 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1774 MenuItem blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1775 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1776 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1777 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1779 // Set the text for the domain menu item.
1780 if (domainSettingsApplied) {
1781 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1783 addOrEditDomain.setTitle(R.string.add_domain_settings);
1786 // Set the status of the menu item checkboxes.
1787 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1788 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1789 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1790 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
1791 easyListMenuItem.setChecked(easyListEnabled);
1792 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1793 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1794 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1795 blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1796 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1797 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1799 // Enable third-party cookies if first-party cookies are enabled.
1800 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1802 // Enable DOM Storage if JavaScript is enabled.
1803 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1805 // Enable Clear Cookies if there are any.
1806 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1808 // Get a count of the number of files in the Local Storage directory.
1809 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1810 int localStorageDirectoryNumberOfFiles = 0;
1811 if (localStorageDirectory.exists()) {
1812 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1815 // Get a count of the number of files in the IndexedDB directory.
1816 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1817 int indexedDBDirectoryNumberOfFiles = 0;
1818 if (indexedDBDirectory.exists()) {
1819 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1822 // Enable Clear DOM Storage if there is any.
1823 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1825 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1826 if (Build.VERSION.SDK_INT < 26) {
1827 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1828 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1831 // Enable Clear Data if any of the submenu items are enabled.
1832 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1834 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
1835 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1837 // Initialize font size variables.
1838 int fontSize = mainWebView.getSettings().getTextZoom();
1839 String fontSizeTitle;
1840 MenuItem selectedFontSizeMenuItem;
1842 // Prepare the font size title and current size menu item.
1845 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1846 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1850 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1851 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1855 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1856 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1860 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1861 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1865 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1866 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1870 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1871 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1875 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1876 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1880 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1881 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1885 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1886 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1890 // Set the font size title and select the current size menu item.
1891 fontSizeMenuItem.setTitle(fontSizeTitle);
1892 selectedFontSizeMenuItem.setChecked(true);
1894 // Run all the other default commands.
1895 super.onPrepareOptionsMenu(menu);
1897 // Display the menu.
1902 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1903 @SuppressLint("SetJavaScriptEnabled")
1904 // removeAllCookies is deprecated, but it is required for API < 21.
1905 @SuppressWarnings("deprecation")
1906 public boolean onOptionsItemSelected(MenuItem menuItem) {
1907 // Get the selected menu item ID.
1908 int menuItemId = menuItem.getItemId();
1910 // Set the commands that relate to the menu entries.
1911 switch (menuItemId) {
1912 case R.id.toggle_javascript:
1913 // Switch the status of javaScriptEnabled.
1914 javaScriptEnabled = !javaScriptEnabled;
1916 // Apply the new JavaScript status.
1917 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1919 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1920 updatePrivacyIcons(true);
1922 // Display a `Snackbar`.
1923 if (javaScriptEnabled) { // JavaScrip is enabled.
1924 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1925 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1926 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1927 } else { // Privacy mode.
1928 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1931 // Reload the WebView.
1932 mainWebView.reload();
1935 case R.id.add_or_edit_domain:
1936 if (domainSettingsApplied) { // Edit the current domain settings.
1937 // Reapply the domain settings on returning to `MainWebViewActivity`.
1938 reapplyDomainSettingsOnRestart = true;
1939 currentDomainName = "";
1941 // Create an intent to launch the domains activity.
1942 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1944 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
1945 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
1946 domainsIntent.putExtra("closeOnBack", true);
1949 startActivity(domainsIntent);
1950 } else { // Add a new domain.
1951 // Apply the new domain settings on returning to `MainWebViewActivity`.
1952 reapplyDomainSettingsOnRestart = true;
1953 currentDomainName = "";
1955 // Get the current domain
1956 Uri currentUri = Uri.parse(formattedUrlString);
1957 String currentDomain = currentUri.getHost();
1959 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1960 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1962 // Create the domain and store the database ID.
1963 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1965 // Create an intent to launch the domains activity.
1966 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1968 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
1969 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
1970 domainsIntent.putExtra("closeOnBack", true);
1973 startActivity(domainsIntent);
1977 case R.id.toggle_first_party_cookies:
1978 // Switch the status of firstPartyCookiesEnabled.
1979 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1981 // Update the menu checkbox.
1982 menuItem.setChecked(firstPartyCookiesEnabled);
1984 // Apply the new cookie status.
1985 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1987 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1988 updatePrivacyIcons(true);
1990 // Display a `Snackbar`.
1991 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1992 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1993 } else if (javaScriptEnabled) { // JavaScript is still enabled.
1994 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1995 } else { // Privacy mode.
1996 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1999 // Reload the WebView.
2000 mainWebView.reload();
2003 case R.id.toggle_third_party_cookies:
2004 if (Build.VERSION.SDK_INT >= 21) {
2005 // Switch the status of thirdPartyCookiesEnabled.
2006 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2008 // Update the menu checkbox.
2009 menuItem.setChecked(thirdPartyCookiesEnabled);
2011 // Apply the new cookie status.
2012 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2014 // Display a `Snackbar`.
2015 if (thirdPartyCookiesEnabled) {
2016 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2018 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2021 // Reload the WebView.
2022 mainWebView.reload();
2023 } // Else do nothing because SDK < 21.
2026 case R.id.toggle_dom_storage:
2027 // Switch the status of domStorageEnabled.
2028 domStorageEnabled = !domStorageEnabled;
2030 // Update the menu checkbox.
2031 menuItem.setChecked(domStorageEnabled);
2033 // Apply the new DOM Storage status.
2034 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2036 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2037 updatePrivacyIcons(true);
2039 // Display a `Snackbar`.
2040 if (domStorageEnabled) {
2041 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2043 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2046 // Reload the WebView.
2047 mainWebView.reload();
2050 // Form data can be removed once the minimum API >= 26.
2051 case R.id.toggle_save_form_data:
2052 // Switch the status of saveFormDataEnabled.
2053 saveFormDataEnabled = !saveFormDataEnabled;
2055 // Update the menu checkbox.
2056 menuItem.setChecked(saveFormDataEnabled);
2058 // Apply the new form data status.
2059 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2061 // Display a `Snackbar`.
2062 if (saveFormDataEnabled) {
2063 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2065 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2068 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2069 updatePrivacyIcons(true);
2071 // Reload the WebView.
2072 mainWebView.reload();
2075 case R.id.clear_cookies:
2076 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2077 .setAction(R.string.undo, v -> {
2078 // Do nothing because everything will be handled by `onDismissed()` below.
2080 .addCallback(new Snackbar.Callback() {
2082 public void onDismissed(Snackbar snackbar, int event) {
2084 // The user pushed the `Undo` button.
2085 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2089 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2091 // `cookieManager.removeAllCookie()` varies by SDK.
2092 if (Build.VERSION.SDK_INT < 21) {
2093 cookieManager.removeAllCookie();
2095 // `null` indicates no callback.
2096 cookieManager.removeAllCookies(null);
2104 case R.id.clear_dom_storage:
2105 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2106 .setAction(R.string.undo, v -> {
2107 // Do nothing because everything will be handled by `onDismissed()` below.
2109 .addCallback(new Snackbar.Callback() {
2111 public void onDismissed(Snackbar snackbar, int event) {
2113 // The user pushed the `Undo` button.
2114 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2118 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2120 // Delete the DOM Storage.
2121 WebStorage webStorage = WebStorage.getInstance();
2122 webStorage.deleteAllData();
2124 // Manually delete the DOM storage files and directories.
2126 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2127 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2129 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2130 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2131 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2132 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2133 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2134 } catch (IOException e) {
2135 // Do nothing if an error is thrown.
2143 // Form data can be remove once the minimum API >= 26.
2144 case R.id.clear_form_data:
2145 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2146 .setAction(R.string.undo, v -> {
2147 // Do nothing because everything will be handled by `onDismissed()` below.
2149 .addCallback(new Snackbar.Callback() {
2151 public void onDismissed(Snackbar snackbar, int event) {
2153 // The user pushed the `Undo` button.
2154 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2158 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2160 // Delete the form data.
2161 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2162 mainWebViewDatabase.clearFormData();
2169 case R.id.font_size_twenty_five_percent:
2170 mainWebView.getSettings().setTextZoom(25);
2173 case R.id.font_size_fifty_percent:
2174 mainWebView.getSettings().setTextZoom(50);
2177 case R.id.font_size_seventy_five_percent:
2178 mainWebView.getSettings().setTextZoom(75);
2181 case R.id.font_size_one_hundred_percent:
2182 mainWebView.getSettings().setTextZoom(100);
2185 case R.id.font_size_one_hundred_twenty_five_percent:
2186 mainWebView.getSettings().setTextZoom(125);
2189 case R.id.font_size_one_hundred_fifty_percent:
2190 mainWebView.getSettings().setTextZoom(150);
2193 case R.id.font_size_one_hundred_seventy_five_percent:
2194 mainWebView.getSettings().setTextZoom(175);
2197 case R.id.font_size_two_hundred_percent:
2198 mainWebView.getSettings().setTextZoom(200);
2201 case R.id.swipe_to_refresh:
2202 // Toggle swipe to refresh.
2203 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2206 case R.id.display_images:
2207 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2208 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2209 mainWebView.reload();
2210 } else { // Images are not currently loaded automatically.
2211 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2214 // Set `onTheFlyDisplayImagesSet`.
2215 onTheFlyDisplayImagesSet = true;
2218 case R.id.view_source:
2219 // Launch the View Source activity.
2220 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2221 startActivity(viewSourceIntent);
2225 // Toggle the EasyList status.
2226 easyListEnabled = !easyListEnabled;
2228 // Update the menu checkbox.
2229 menuItem.setChecked(easyListEnabled);
2231 // Reload the main WebView.
2232 mainWebView.reload();
2235 case R.id.easyprivacy:
2236 // Toggle the EasyPrivacy status.
2237 easyPrivacyEnabled = !easyPrivacyEnabled;
2239 // Update the menu checkbox.
2240 menuItem.setChecked(easyPrivacyEnabled);
2242 // Reload the main WebView.
2243 mainWebView.reload();
2246 case R.id.fanboys_annoyance_list:
2247 // Toggle Fanboy's Annoyance List status.
2248 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2250 // Update the menu checkbox.
2251 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2253 // Update the staus of Fanboy's Social Blocking List.
2254 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2255 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2257 // Reload the main WebView.
2258 mainWebView.reload();
2261 case R.id.fanboys_social_blocking_list:
2262 // Toggle Fanboy's Social Blocking List status.
2263 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2265 // Update the menu checkbox.
2266 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2268 // Reload the main WebView.
2269 mainWebView.reload();
2272 case R.id.block_all_third_party_requests:
2273 //Toggle the third-party requests blocker status.
2274 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2276 // Update the menu checkbox.
2277 menuItem.setChecked(blockAllThirdPartyRequests);
2279 // Reload the main WebView.
2280 mainWebView.reload();
2284 // Setup the share string.
2285 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2287 // Create the share intent.
2288 Intent shareIntent = new Intent();
2289 shareIntent.setAction(Intent.ACTION_SEND);
2290 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2291 shareIntent.setType("text/plain");
2294 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2297 case R.id.find_on_page:
2298 // Hide the URL app bar.
2299 supportAppBar.setVisibility(View.GONE);
2301 // Show the Find on Page `RelativeLayout`.
2302 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2304 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2305 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2306 findOnPageEditText.postDelayed(() -> {
2307 // Set the focus on `findOnPageEditText`.
2308 findOnPageEditText.requestFocus();
2310 // Display the keyboard. `0` sets no input flags.
2311 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2316 // Get a `PrintManager` instance.
2317 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2319 // Convert `mainWebView` to `printDocumentAdapter`.
2320 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2322 // Remove the lint error below that `printManager` might be `null`.
2323 assert printManager != null;
2325 // Print the document. The print attributes are `null`.
2326 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2329 case R.id.add_to_homescreen:
2330 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2331 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2332 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2334 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2338 mainWebView.reload();
2341 case R.id.ad_consent:
2342 // Display the ad consent dialog.
2343 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2344 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2348 // Don't consume the event.
2349 return super.onOptionsItemSelected(menuItem);
2353 // removeAllCookies is deprecated, but it is required for API < 21.
2354 @SuppressWarnings("deprecation")
2356 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2357 int menuItemId = menuItem.getItemId();
2359 switch (menuItemId) {
2365 if (mainWebView.canGoBack()) {
2366 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2367 formattedUrlString = "";
2369 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2370 navigatingHistory = true;
2372 // Load the previous website in the history.
2373 mainWebView.goBack();
2378 if (mainWebView.canGoForward()) {
2379 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2380 formattedUrlString = "";
2382 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2383 navigatingHistory = true;
2385 // Load the next website in the history.
2386 mainWebView.goForward();
2391 // Get the `WebBackForwardList`.
2392 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2394 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2395 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2396 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2400 // Launch the requests activity.
2401 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2402 startActivity(requestsIntent);
2405 case R.id.downloads:
2406 // Launch the system Download Manager.
2407 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2409 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2410 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2412 startActivity(downloadManagerIntent);
2416 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2417 reapplyDomainSettingsOnRestart = true;
2418 currentDomainName = "";
2420 // Launch the domains activity.
2421 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2422 startActivity(domainsIntent);
2426 // Set the flag to reapply app settings on restart when returning from Settings.
2427 reapplyAppSettingsOnRestart = true;
2429 // Set the flag to reapply the domain settings on restart when returning from Settings.
2430 reapplyDomainSettingsOnRestart = true;
2431 currentDomainName = "";
2433 // Launch the settings activity.
2434 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2435 startActivity(settingsIntent);
2439 // Launch `GuideActivity`.
2440 Intent guideIntent = new Intent(this, GuideActivity.class);
2441 startActivity(guideIntent);
2445 // Launch `AboutActivity`.
2446 Intent aboutIntent = new Intent(this, AboutActivity.class);
2447 startActivity(aboutIntent);
2450 case R.id.clearAndExit:
2451 // Get a handle for `sharedPreferences`. `this` references the current context.
2452 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2454 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2457 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2458 // The command to remove cookies changed slightly in API 21.
2459 if (Build.VERSION.SDK_INT >= 21) {
2460 cookieManager.removeAllCookies(null);
2462 cookieManager.removeAllCookie();
2465 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2467 // We have to use two commands because `Runtime.exec()` does not like `*`.
2468 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2469 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2470 } catch (IOException e) {
2471 // Do nothing if an error is thrown.
2475 // Clear DOM storage.
2476 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2477 // Ask `WebStorage` to clear the DOM storage.
2478 WebStorage webStorage = WebStorage.getInstance();
2479 webStorage.deleteAllData();
2481 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2483 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2484 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2486 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2487 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2488 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2489 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2490 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2491 } catch (IOException e) {
2492 // Do nothing if an error is thrown.
2496 // Clear form data if the API < 26.
2497 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2498 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2499 webViewDatabase.clearFormData();
2501 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2503 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2504 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2505 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2506 } catch (IOException e) {
2507 // Do nothing if an error is thrown.
2512 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2513 // `true` includes disk files.
2514 mainWebView.clearCache(true);
2516 // Manually delete the cache directories.
2518 // Delete the main cache directory.
2519 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2521 // Delete the secondary `Service Worker` cache directory.
2522 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2523 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2524 } catch (IOException e) {
2525 // Do nothing if an error is thrown.
2529 // Clear SSL certificate preferences.
2530 mainWebView.clearSslPreferences();
2532 // Clear the back/forward history.
2533 mainWebView.clearHistory();
2535 // Clear `formattedUrlString`.
2536 formattedUrlString = null;
2538 // Clear `customHeaders`.
2539 customHeaders.clear();
2541 // Detach all views from `mainWebViewRelativeLayout`.
2542 mainWebViewRelativeLayout.removeAllViews();
2544 // Destroy the internal state of `mainWebView`.
2545 mainWebView.destroy();
2547 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2548 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2549 if (clearEverything) {
2551 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2552 } catch (IOException e) {
2553 // Do nothing if an error is thrown.
2557 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2558 if (Build.VERSION.SDK_INT >= 21) {
2559 finishAndRemoveTask();
2564 // Remove the terminated program from RAM. The status code is `0`.
2569 // Close the navigation drawer.
2570 drawerLayout.closeDrawer(GravityCompat.START);
2575 public void onPostCreate(Bundle savedInstanceState) {
2576 super.onPostCreate(savedInstanceState);
2578 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2579 drawerToggle.syncState();
2583 public void onConfigurationChanged(Configuration newConfig) {
2584 super.onConfigurationChanged(newConfig);
2586 // Reload the ad for the free flavor if we are not in full screen mode.
2587 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2588 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2589 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2592 // `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:
2593 // https://code.google.com/p/android/issues/detail?id=20493#c8
2594 // ActivityCompat.invalidateOptionsMenu(this);
2598 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2599 // Store the `HitTestResult`.
2600 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2603 final String imageUrl;
2604 final String linkUrl;
2606 // Get a handle for the `ClipboardManager`.
2607 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2609 // Remove the lint errors below that `clipboardManager` might be `null`.
2610 assert clipboardManager != null;
2612 switch (hitTestResult.getType()) {
2613 // `SRC_ANCHOR_TYPE` is a link.
2614 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2615 // Get the target URL.
2616 linkUrl = hitTestResult.getExtra();
2618 // Set the target URL as the title of the `ContextMenu`.
2619 menu.setHeaderTitle(linkUrl);
2621 // Add a Load URL entry.
2622 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2627 // Add a Copy URL entry.
2628 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2629 // Save the link URL in a `ClipData`.
2630 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2632 // Set the `ClipData` as the clipboard's primary clip.
2633 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2637 // Add a Download URL entry.
2638 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2639 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2640 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2641 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2643 // Store the variables for future use by `onRequestPermissionsResult()`.
2644 downloadUrl = linkUrl;
2645 downloadContentDisposition = "none";
2646 downloadContentLength = -1;
2648 // Show a dialog if the user has previously denied the permission.
2649 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2650 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2651 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2653 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2654 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2655 } else { // Show the permission request directly.
2656 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2657 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2659 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2660 // Get a handle for the download file alert dialog.
2661 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2663 // Show the download file alert dialog.
2664 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2669 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2670 menu.add(R.string.cancel);
2673 case WebView.HitTestResult.EMAIL_TYPE:
2674 // Get the target URL.
2675 linkUrl = hitTestResult.getExtra();
2677 // Set the target URL as the title of the `ContextMenu`.
2678 menu.setHeaderTitle(linkUrl);
2680 // Add a `Write Email` entry.
2681 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2682 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2683 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2685 // Parse the url and set it as the data for the `Intent`.
2686 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2688 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2689 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2692 startActivity(emailIntent);
2696 // Add a `Copy Email Address` entry.
2697 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2698 // Save the email address in a `ClipData`.
2699 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2701 // Set the `ClipData` as the clipboard's primary clip.
2702 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2706 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2707 menu.add(R.string.cancel);
2710 // `IMAGE_TYPE` is an image.
2711 case WebView.HitTestResult.IMAGE_TYPE:
2712 // Get the image URL.
2713 imageUrl = hitTestResult.getExtra();
2715 // Set the image URL as the title of the `ContextMenu`.
2716 menu.setHeaderTitle(imageUrl);
2718 // Add a `View Image` entry.
2719 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2724 // Add a `Download Image` entry.
2725 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2726 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2727 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2728 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2730 // Store the image URL for use by `onRequestPermissionResult()`.
2731 downloadImageUrl = imageUrl;
2733 // Show a dialog if the user has previously denied the permission.
2734 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2735 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2736 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2738 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2739 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2740 } else { // Show the permission request directly.
2741 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2742 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2744 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2745 // Get a handle for the download image alert dialog.
2746 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2748 // Show the download image alert dialog.
2749 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2754 // Add a `Copy URL` entry.
2755 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2756 // Save the image URL in a `ClipData`.
2757 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2759 // Set the `ClipData` as the clipboard's primary clip.
2760 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2764 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2765 menu.add(R.string.cancel);
2769 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2770 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2771 // Get the image URL.
2772 imageUrl = hitTestResult.getExtra();
2774 // Set the image URL as the title of the `ContextMenu`.
2775 menu.setHeaderTitle(imageUrl);
2777 // Add a `View Image` entry.
2778 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2783 // Add a `Download Image` entry.
2784 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2785 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2786 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2787 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2789 // Store the image URL for use by `onRequestPermissionResult()`.
2790 downloadImageUrl = imageUrl;
2792 // Show a dialog if the user has previously denied the permission.
2793 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2794 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2795 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2797 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2798 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2799 } else { // Show the permission request directly.
2800 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2801 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2803 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2804 // Get a handle for the download image alert dialog.
2805 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2807 // Show the download image alert dialog.
2808 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2813 // Add a `Copy URL` entry.
2814 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2815 // Save the image URL in a `ClipData`.
2816 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2818 // Set the `ClipData` as the clipboard's primary clip.
2819 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2823 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2824 menu.add(R.string.cancel);
2830 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2831 // Get the `EditTexts` from the `dialogFragment`.
2832 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2833 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2835 // Extract the strings from the `EditTexts`.
2836 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2837 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2839 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2840 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2841 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2842 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2844 // Display the new bookmark below the current items in the (0 indexed) list.
2845 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2847 // Create the bookmark.
2848 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2850 // Update `bookmarksCursor` with the current contents of this folder.
2851 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2853 // Update the `ListView`.
2854 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2856 // Scroll to the new bookmark.
2857 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2861 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2862 // Get handles for the views in `dialogFragment`.
2863 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2864 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2865 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2867 // Get new folder name string.
2868 String folderNameString = createFolderNameEditText.getText().toString();
2870 // Get the new folder icon `Bitmap`.
2871 Bitmap folderIconBitmap;
2872 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2873 // Get the default folder icon and convert it to a `Bitmap`.
2874 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2875 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2876 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2877 } else { // Use the `WebView` favorite icon.
2878 folderIconBitmap = favoriteIconBitmap;
2881 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2882 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2883 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2884 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2886 // Move all the bookmarks down one in the display order.
2887 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2888 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2889 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2892 // Create the folder, which will be placed at the top of the `ListView`.
2893 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2895 // Update `bookmarksCursor` with the current contents of this folder.
2896 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2898 // Update the `ListView`.
2899 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2901 // Scroll to the new folder.
2902 bookmarksListView.setSelection(0);
2906 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2907 // Get the shortcut name.
2908 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2909 String shortcutNameString = shortcutNameEditText.getText().toString();
2911 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2912 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2914 // Setup the shortcut intent.
2915 Intent shortcutIntent = new Intent();
2916 shortcutIntent.setAction(Intent.ACTION_VIEW);
2917 shortcutIntent.setData(Uri.parse(formattedUrlString));
2919 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2920 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2922 // Add the required fields to the shortcut info builder.
2923 shortcutInfoBuilder.setIcon(favoriteIcon);
2924 shortcutInfoBuilder.setIntent(shortcutIntent);
2925 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2927 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2928 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2932 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2933 switch (downloadType) {
2934 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2935 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2936 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2939 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2940 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2941 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2947 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
2948 switch (requestCode) {
2949 case DOWNLOAD_FILE_REQUEST_CODE:
2950 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2951 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2953 // On API 23, displaying the fragment must be delayed or the app will crash.
2954 if (Build.VERSION.SDK_INT == 23) {
2955 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2957 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2960 // Reset the download variables.
2962 downloadContentDisposition = "";
2963 downloadContentLength = 0;
2966 case DOWNLOAD_IMAGE_REQUEST_CODE:
2967 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2968 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2970 // On API 23, displaying the fragment must be delayed or the app will crash.
2971 if (Build.VERSION.SDK_INT == 23) {
2972 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2974 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2977 // Reset the image URL variable.
2978 downloadImageUrl = "";
2984 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2985 // Download the image if it has an HTTP or HTTPS URI.
2986 if (imageUrl.startsWith("http")) {
2987 // Get a handle for the system `DOWNLOAD_SERVICE`.
2988 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2990 // Parse `imageUrl`.
2991 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2993 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2994 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2995 if (firstPartyCookiesEnabled) {
2996 // Get the cookies for `imageUrl`.
2997 String cookies = cookieManager.getCookie(imageUrl);
2999 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3000 downloadRequest.addRequestHeader("Cookie", cookies);
3003 // Get the file name from the dialog fragment.
3004 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3005 String imageName = downloadImageNameEditText.getText().toString();
3007 // Specify the download location.
3008 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3009 // Download to the public download directory.
3010 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3011 } else { // External write permission denied.
3012 // Download to the app's external download directory.
3013 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3016 // Allow `MediaScanner` to index the download if it is a media file.
3017 downloadRequest.allowScanningByMediaScanner();
3019 // Add the URL as the description for the download.
3020 downloadRequest.setDescription(imageUrl);
3022 // Show the download notification after the download is completed.
3023 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3025 // Remove the lint warning below that `downloadManager` might be `null`.
3026 assert downloadManager != null;
3028 // Initiate the download.
3029 downloadManager.enqueue(downloadRequest);
3030 } else { // The image is not an HTTP or HTTPS URI.
3031 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3036 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3037 // Download the file if it has an HTTP or HTTPS URI.
3038 if (downloadUrl.startsWith("http")) {
3039 // Get a handle for the system `DOWNLOAD_SERVICE`.
3040 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3042 // Parse `downloadUrl`.
3043 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3045 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3046 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3047 if (firstPartyCookiesEnabled) {
3048 // Get the cookies for `downloadUrl`.
3049 String cookies = cookieManager.getCookie(downloadUrl);
3051 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3052 downloadRequest.addRequestHeader("Cookie", cookies);
3055 // Get the file name from the dialog fragment.
3056 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3057 String fileName = downloadFileNameEditText.getText().toString();
3059 // Specify the download location.
3060 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3061 // Download to the public download directory.
3062 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3063 } else { // External write permission denied.
3064 // Download to the app's external download directory.
3065 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3068 // Allow `MediaScanner` to index the download if it is a media file.
3069 downloadRequest.allowScanningByMediaScanner();
3071 // Add the URL as the description for the download.
3072 downloadRequest.setDescription(downloadUrl);
3074 // Show the download notification after the download is completed.
3075 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3077 // Remove the lint warning below that `downloadManager` might be `null`.
3078 assert downloadManager != null;
3080 // Initiate the download.
3081 downloadManager.enqueue(downloadRequest);
3082 } else { // The download is not an HTTP or HTTPS URI.
3083 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3088 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3089 // Get handles for the views from `dialogFragment`.
3090 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3091 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3092 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3094 // Store the bookmark strings.
3095 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3096 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3098 // Update the bookmark.
3099 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3100 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3101 } else { // Update the bookmark using the `WebView` favorite icon.
3102 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3103 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3104 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3105 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3107 // Update the bookmark and the favorite icon.
3108 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3111 // Update `bookmarksCursor` with the current contents of this folder.
3112 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3114 // Update the `ListView`.
3115 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3119 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3120 // Get handles for the views from `dialogFragment`.
3121 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3122 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3123 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3124 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3126 // Get the new folder name.
3127 String newFolderNameString = editFolderNameEditText.getText().toString();
3129 // Check if the favorite icon has changed.
3130 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3131 // Update the name in the database.
3132 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3133 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3134 // Get the new folder icon `Bitmap`.
3135 Bitmap folderIconBitmap;
3136 if (defaultFolderIconRadioButton.isChecked()) {
3137 // Get the default folder icon and convert it to a `Bitmap`.
3138 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3139 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3140 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3141 } else { // Use the `WebView` favorite icon.
3142 folderIconBitmap = favoriteIconBitmap;
3145 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3146 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3147 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3148 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3150 // Update the folder icon in the database.
3151 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3152 } else { // The folder icon and the name have changed.
3153 // Get the new folder icon `Bitmap`.
3154 Bitmap folderIconBitmap;
3155 if (defaultFolderIconRadioButton.isChecked()) {
3156 // Get the default folder icon and convert it to a `Bitmap`.
3157 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3158 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3159 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3160 } else { // Use the `WebView` favorite icon.
3161 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3164 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3165 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3166 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3167 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3169 // Update the folder name and icon in the database.
3170 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3173 // Update `bookmarksCursor` with the current contents of this folder.
3174 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3176 // Update the `ListView`.
3177 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3181 public void onHttpAuthenticationCancel() {
3182 // Cancel the `HttpAuthHandler`.
3183 httpAuthHandler.cancel();
3187 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3188 // Get handles for the `EditTexts`.
3189 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3190 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3192 // Proceed with the HTTP authentication.
3193 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3196 public void viewSslCertificate(View view) {
3197 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3198 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3199 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3203 public void onSslErrorCancel() {
3204 sslErrorHandler.cancel();
3208 public void onSslErrorProceed() {
3209 sslErrorHandler.proceed();
3213 public void onSslMismatchBack() {
3214 if (mainWebView.canGoBack()) { // There is a back page in the history.
3215 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3216 formattedUrlString = "";
3218 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3219 navigatingHistory = true;
3222 mainWebView.goBack();
3223 } else { // There are no pages to go back to.
3224 // Load a blank page
3230 public void onSslMismatchProceed() {
3231 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3232 ignorePinnedSslCertificate = true;
3236 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3237 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3238 formattedUrlString = "";
3240 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3241 navigatingHistory = true;
3243 // Load the history entry.
3244 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3248 public void onClearHistory() {
3249 // Clear the history.
3250 mainWebView.clearHistory();
3253 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3255 public void onBackPressed() {
3256 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3257 // Close the navigation drawer.
3258 drawerLayout.closeDrawer(GravityCompat.START);
3259 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3260 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3261 // close the bookmarks drawer.
3262 drawerLayout.closeDrawer(GravityCompat.END);
3263 } else { // A subfolder is displayed.
3264 // Place the former parent folder in `currentFolder`.
3265 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3267 // Load the new folder.
3268 loadBookmarksFolder();
3271 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3272 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3273 formattedUrlString = "";
3275 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3276 navigatingHistory = true;
3279 mainWebView.goBack();
3280 } else { // There isn't anything to do in Privacy Browser.
3281 // Pass `onBackPressed()` to the system.
3282 super.onBackPressed();
3286 // 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.
3288 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3289 // File uploads only work on API >= 21.
3290 if (Build.VERSION.SDK_INT >= 21) {
3291 // Pass the file to the WebView.
3292 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3296 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3297 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3298 String unformattedUrlString = urlTextBox.getText().toString().trim();
3300 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3301 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3302 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3303 if (!unformattedUrlString.startsWith("http")) {
3304 unformattedUrlString = "http://" + unformattedUrlString;
3307 // Initialize `unformattedUrl`.
3308 URL unformattedUrl = null;
3310 // 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.
3312 unformattedUrl = new URL(unformattedUrlString);
3313 } catch (MalformedURLException e) {
3314 e.printStackTrace();
3317 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3318 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3319 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3320 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3321 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3322 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3325 Uri.Builder formattedUri = new Uri.Builder();
3326 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3328 // Decode `formattedUri` as a `String` in `UTF-8`.
3329 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3330 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3331 // Load a blank string.
3332 formattedUrlString = "";
3333 } else { // Search for the contents of the URL box.
3334 // Sanitize the search input and convert it to a search.
3335 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3337 // Add the base search URL.
3338 formattedUrlString = searchURL + encodedUrlString;
3341 // 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.
3342 urlTextBox.clearFocus();
3345 loadUrl(formattedUrlString);
3348 private void loadUrl(String url) {// Apply any custom domain settings.
3349 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3350 formattedUrlString = url;
3352 // Apply the domain settings.
3353 applyDomainSettings(url, true, false);
3355 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3356 urlIsLoading = true;
3359 mainWebView.loadUrl(url, customHeaders);
3362 public void findPreviousOnPage(View view) {
3363 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3364 mainWebView.findNext(false);
3367 public void findNextOnPage(View view) {
3368 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3369 mainWebView.findNext(true);
3372 public void closeFindOnPage(View view) {
3373 // Delete the contents of `find_on_page_edittext`.
3374 findOnPageEditText.setText(null);
3376 // Clear the highlighted phrases.
3377 mainWebView.clearMatches();
3379 // Hide the Find on Page `RelativeLayout`.
3380 findOnPageLinearLayout.setVisibility(View.GONE);
3382 // Show the URL app bar.
3383 supportAppBar.setVisibility(View.VISIBLE);
3385 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3386 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3389 private void applyAppSettings() {
3390 // Get a handle for the shared preferences.
3391 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3393 // Store the values from the shared preferences in variables.
3394 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3395 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3396 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3397 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3398 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3399 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3400 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3401 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3402 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3403 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3404 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3405 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3406 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3408 // Set the homepage, search, and proxy options.
3409 if (proxyThroughOrbot) { // Set the Tor options.
3410 // Set `torHomepageString` as `homepage`.
3411 homepage = torHomepageString;
3413 // If formattedUrlString is null assign the homepage to it.
3414 if (formattedUrlString == null) {
3415 formattedUrlString = homepage;
3418 // Set the search URL.
3419 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3420 searchURL = torSearchCustomURLString;
3421 } else { // Use the string from the pre-built list.
3422 searchURL = torSearchString;
3425 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3426 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3428 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3430 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3432 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3435 // Display a message to the user if waiting for Orbot.
3436 if (!orbotStatus.equals("ON")) {
3437 // Set `waitingForOrbot`.
3438 waitingForOrbot = true;
3440 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3441 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3443 } else { // Set the non-Tor options.
3444 // Set `homepageString` as `homepage`.
3445 homepage = homepageString;
3447 // If formattedUrlString is null assign the homepage to it.
3448 if (formattedUrlString == null) {
3449 formattedUrlString = homepage;
3452 // Set the search URL.
3453 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3454 searchURL = searchCustomURLString;
3455 } else { // Use the string from the pre-built list.
3456 searchURL = searchString;
3459 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3460 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3462 // Set the default `appBar` background. `this` refers to the context.
3464 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3466 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3469 // Reset `waitingForOrbot.
3470 waitingForOrbot = false;
3473 // Set Do Not Track status.
3474 if (doNotTrackEnabled) {
3475 customHeaders.put("DNT", "1");
3477 customHeaders.remove("DNT");
3480 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3481 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3482 if (hideSystemBarsOnFullscreen) { // Hide everything.
3483 // Remove the translucent navigation setting if it is currently flagged.
3484 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3486 // Remove the translucent status bar overlay.
3487 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3489 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3490 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3492 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3493 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3494 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3496 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3497 } else { // Hide everything except the status and navigation bars.
3498 // Add the translucent status flag if it is unset.
3499 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3501 if (translucentNavigationBarOnFullscreen) {
3502 // Set the navigation bar to be translucent.
3503 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3505 // Set the navigation bar to be black.
3506 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3509 } else { // Switch to normal viewing mode.
3510 // Reset `inFullScreenBrowsingMode` to `false`.
3511 inFullScreenBrowsingMode = false;
3513 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3514 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3518 // Show the `BannerAd` in the free flavor.
3519 if (BuildConfig.FLAVOR.contentEquals("free")) {
3520 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3521 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3524 // Remove the translucent navigation bar flag if it is set.
3525 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3527 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3528 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3530 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3531 rootCoordinatorLayout.setSystemUiVisibility(0);
3533 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3534 rootCoordinatorLayout.setFitsSystemWindows(true);
3538 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3539 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3540 @SuppressWarnings("deprecation")
3541 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3542 // Parse the URL into a URI.
3543 Uri uri = Uri.parse(url);
3545 // Extract the domain from `uri`.
3546 String hostName = uri.getHost();
3548 // Initialize `loadingNewDomainName`.
3549 boolean loadingNewDomainName;
3551 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3552 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3553 //noinspection SimplifiableIfStatement
3554 if ((hostName == null) || (currentDomainName == null)) {
3555 loadingNewDomainName = true;
3556 } else { // Determine if `hostName` equals `currentDomainName`.
3557 loadingNewDomainName = !hostName.equals(currentDomainName);
3560 // Strings don't like to be null.
3561 if (hostName == null) {
3565 // 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.
3566 if (loadingNewDomainName) {
3567 // Set the new `hostname` as the `currentDomainName`.
3568 currentDomainName = hostName;
3570 // Reset `ignorePinnedSslCertificate`.
3571 ignorePinnedSslCertificate = false;
3573 // Reset the favorite icon if specified.
3574 if (resetFavoriteIcon) {
3575 favoriteIconBitmap = favoriteIconDefaultBitmap;
3576 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3579 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3580 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3581 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3583 // Get a full cursor from `domainsDatabaseHelper`.
3584 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3586 // Initialize `domainSettingsSet`.
3587 Set<String> domainSettingsSet = new HashSet<>();
3589 // Get the domain name column index.
3590 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3592 // Populate `domainSettingsSet`.
3593 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3594 // Move `domainsCursor` to the current row.
3595 domainNameCursor.moveToPosition(i);
3597 // Store the domain name in `domainSettingsSet`.
3598 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3601 // Close `domainNameCursor.
3602 domainNameCursor.close();
3604 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3605 domainSettingsApplied = false;
3606 String domainNameInDatabase = null;
3608 // Check the hostname.
3609 if (domainSettingsSet.contains(hostName)) {
3610 domainSettingsApplied = true;
3611 domainNameInDatabase = hostName;
3614 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3615 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3616 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3617 // Apply the domain settings.
3618 domainSettingsApplied = true;
3620 // Store the applied domain names as it appears in the database.
3621 domainNameInDatabase = "*." + hostName;
3624 // Strip out the lowest subdomain of of the host name.
3625 hostName = hostName.substring(hostName.indexOf(".") + 1);
3629 // Get a handle for the shared preference.
3630 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3632 // Store the general preference information.
3633 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3634 String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3635 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3636 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3637 nightMode = sharedPreferences.getBoolean("night_mode", false);
3639 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3640 // Get a cursor for the current host and move it to the first position.
3641 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3642 currentHostDomainSettingsCursor.moveToFirst();
3644 // Get the settings from the cursor.
3645 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3646 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3647 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3648 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3649 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3650 // Form data can be removed once the minimum API >= 26.
3651 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3652 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3653 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3654 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3655 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3656 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3657 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3658 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3659 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3660 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3661 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3662 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3663 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3664 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3665 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3666 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3667 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3668 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3670 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3671 switch (nightModeInt) {
3672 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3676 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3681 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3683 javaScriptEnabled = true;
3686 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3687 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3688 pinnedDomainSslStartDate = null;
3690 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3693 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3694 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3695 pinnedDomainSslEndDate = null;
3697 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3700 // Close `currentHostDomainSettingsCursor`.
3701 currentHostDomainSettingsCursor.close();
3703 // Apply the domain settings.
3704 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3705 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3706 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3708 // Apply the form data setting if the API < 26.
3709 if (Build.VERSION.SDK_INT < 26) {
3710 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3713 // Apply the font size.
3714 if (fontSize == 0) { // Apply the default font size.
3715 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3716 } else { // Apply the specified font size.
3717 mainWebView.getSettings().setTextZoom(fontSize);
3720 // Set third-party cookies status if API >= 21.
3721 if (Build.VERSION.SDK_INT >= 21) {
3722 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3725 // 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.
3726 // <https://redmine.stoutner.com/issues/160>
3727 if (!urlIsLoading) {
3728 // Set the user agent.
3729 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3730 // Get the array position of the default user agent name.
3731 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3733 // Set the user agent according to the system default.
3734 switch (defaultUserAgentArrayPosition) {
3735 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3736 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3737 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3740 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3741 // Set the user agent to `""`, which uses the default value.
3742 mainWebView.getSettings().setUserAgentString("");
3745 case SETTINGS_CUSTOM_USER_AGENT:
3746 // Set the custom user agent.
3747 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3751 // Get the user agent string from the user agent data array
3752 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3754 } else { // Set the user agent according to the stored name.
3755 // Get the array position of the user agent name.
3756 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3758 switch (userAgentArrayPosition) {
3759 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3760 mainWebView.getSettings().setUserAgentString(userAgentName);
3763 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3764 // Set the user agent to `""`, which uses the default value.
3765 mainWebView.getSettings().setUserAgentString("");
3769 // Get the user agent string from the user agent data array.
3770 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3774 // Set swipe to refresh.
3775 switch (swipeToRefreshInt) {
3776 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3777 // Set swipe to refresh according to the default.
3778 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3781 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3782 // Enable swipe to refresh.
3783 swipeRefreshLayout.setEnabled(true);
3786 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3787 // Disable swipe to refresh.
3788 swipeRefreshLayout.setEnabled(false);
3791 // Store the applied user agent string, which is used in the View Source activity.
3792 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3795 // 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.
3797 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3799 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3801 } else { // The new URL does not have custom domain settings. Load the defaults.
3802 // Store the values from `sharedPreferences` in variables.
3803 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3804 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3805 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3806 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3807 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false); // Form data can be removed once the minimum API >= 26.
3808 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3809 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3810 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3811 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3812 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
3814 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3816 javaScriptEnabled = true;
3819 // Apply the default settings.
3820 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3821 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3822 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3823 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3824 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3826 // Apply the form data setting if the API < 26.
3827 if (Build.VERSION.SDK_INT < 26) {
3828 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3831 // Reset the pinned SSL certificate information.
3832 domainSettingsDatabaseId = -1;
3833 pinnedDomainSslCertificate = false;
3834 pinnedDomainSslIssuedToCNameString = "";
3835 pinnedDomainSslIssuedToONameString = "";
3836 pinnedDomainSslIssuedToUNameString = "";
3837 pinnedDomainSslIssuedByCNameString = "";
3838 pinnedDomainSslIssuedByONameString = "";
3839 pinnedDomainSslIssuedByUNameString = "";
3840 pinnedDomainSslStartDate = null;
3841 pinnedDomainSslEndDate = null;
3843 // Set third-party cookies status if API >= 21.
3844 if (Build.VERSION.SDK_INT >= 21) {
3845 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3848 // 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.
3849 // <https://redmine.stoutner.com/issues/160>
3850 if (!urlIsLoading) {
3851 // Get the array position of the user agent name.
3852 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3854 // Set the user agent.
3855 switch (userAgentArrayPosition) {
3856 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3857 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3858 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3861 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3862 // Set the user agent to `""`, which uses the default value.
3863 mainWebView.getSettings().setUserAgentString("");
3866 case SETTINGS_CUSTOM_USER_AGENT:
3867 // Set the custom user agent.
3868 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3872 // Get the user agent string from the user agent data array
3873 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3876 // Store the applied user agent string, which is used in the View Source activity.
3877 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3880 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3881 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3884 // Close `domainsDatabaseHelper`.
3885 domainsDatabaseHelper.close();
3887 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3888 onTheFlyDisplayImagesSet = false;
3889 setDisplayWebpageImages();
3891 // Update the privacy icons, but only if `mainMenu` has already been populated.
3892 if (mainMenu != null) {
3893 updatePrivacyIcons(true);
3897 // Reload the website if returning from the Domains activity.
3898 if (reloadWebsite) {
3899 mainWebView.reload();
3903 private void setDisplayWebpageImages() {
3904 if (!onTheFlyDisplayImagesSet) {
3905 if (domainSettingsApplied) { // Custom domain settings are applied.
3906 switch (displayWebpageImagesInt) {
3907 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3908 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3911 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3912 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3915 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3916 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3919 } else { // Default settings are applied.
3920 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3925 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3926 // Get handles for the menu items.
3927 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3928 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3929 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3930 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
3932 // Update the privacy icon.
3933 if (javaScriptEnabled) { // JavaScript is enabled.
3934 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3935 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3936 privacyMenuItem.setIcon(R.drawable.warning);
3937 } else { // All the dangerous features are disabled.
3938 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3941 // Update the first-party cookies icon.
3942 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3943 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3944 } else { // First-party cookies are disabled.
3946 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3948 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3952 // Update the DOM storage icon.
3953 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3954 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3955 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3957 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3959 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3961 } else { // JavaScript is disabled, so DOM storage is ghosted.
3963 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3965 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3969 // Update the refresh icon.
3971 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3973 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3976 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3977 if (runInvalidateOptionsMenu) {
3978 invalidateOptionsMenu();
3982 private void highlightUrlText() {
3983 String urlString = urlTextBox.getText().toString();
3985 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3986 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3987 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3988 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3991 // Get the index of the `/` immediately after the domain name.
3992 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3994 // De-emphasize the text after the domain name.
3995 if (endOfDomainName > 0) {
3996 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4000 private void loadBookmarksFolder() {
4001 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4002 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4004 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4005 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4007 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4008 // Inflate the individual item layout. `false` does not attach it to the root.
4009 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4013 public void bindView(View view, Context context, Cursor cursor) {
4014 // Get handles for the views.
4015 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4016 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4018 // Get the favorite icon byte array from the cursor.
4019 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4021 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4022 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4024 // Display the bitmap in `bookmarkFavoriteIcon`.
4025 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4027 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4028 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4029 bookmarkNameTextView.setText(bookmarkNameString);
4031 // Make the font bold for folders.
4032 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4033 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4034 } else { // Reset the font to default for normal bookmarks.
4035 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4040 // Populate the `ListView` with the adapter.
4041 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4043 // Set the bookmarks drawer title.
4044 if (currentBookmarksFolder.isEmpty()) {
4045 bookmarksTitleTextView.setText(R.string.bookmarks);
4047 bookmarksTitleTextView.setText(currentBookmarksFolder);