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;
199 public static String ultraPrivacyVersion;
201 // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`. They are also used in `onCreate()` and `onPrepareOptionsMenu()`.
202 public static List<String[]> resourceRequests;
203 public static String[] whiteListResultStringArray;
204 int easyListBlockedRequests;
205 int easyPrivacyBlockedRequests;
206 int fanboysAnnoyanceListBlockedRequests;
207 int fanboysSocialBlockingListBlockedRequests;
208 int ultraPrivacyBlockedRequests;
209 int thirdPartyBlockedRequests;
211 public final static int REQUEST_DISPOSITION = 0;
212 public final static int REQUEST_URL = 1;
213 public final static int REQUEST_BLOCKLIST = 2;
214 public final static int REQUEST_SUBLIST = 3;
215 public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
216 public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
218 public final static int REQUEST_DEFAULT = 0;
219 public final static int REQUEST_ALLOWED = 1;
220 public final static int REQUEST_THIRD_PARTY = 2;
221 public final static int REQUEST_BLOCKED = 3;
223 public final static int MAIN_WHITELIST = 1;
224 public final static int FINAL_WHITELIST = 2;
225 public final static int DOMAIN_WHITELIST = 3;
226 public final static int DOMAIN_INITIAL_WHITELIST = 4;
227 public final static int DOMAIN_FINAL_WHITELIST = 5;
228 public final static int THIRD_PARTY_WHITELIST = 6;
229 public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
230 public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
232 public final static int MAIN_BLACKLIST = 9;
233 public final static int INITIAL_BLACKLIST = 10;
234 public final static int FINAL_BLACKLIST = 11;
235 public final static int DOMAIN_BLACKLIST = 12;
236 public final static int DOMAIN_INITIAL_BLACKLIST = 13;
237 public final static int DOMAIN_FINAL_BLACKLIST = 14;
238 public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
239 public final static int THIRD_PARTY_BLACKLIST = 16;
240 public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
241 public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
242 public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
243 public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
244 public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
245 public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
247 // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
248 // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
249 public static boolean blockAllThirdPartyRequests;
251 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
252 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
253 public static String currentBookmarksFolder;
255 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
256 public static int domainSettingsDatabaseId;
258 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
259 public static String pinnedDomainSslIssuedToCNameString;
260 public static String pinnedDomainSslIssuedToONameString;
261 public static String pinnedDomainSslIssuedToUNameString;
262 public static String pinnedDomainSslIssuedByCNameString;
263 public static String pinnedDomainSslIssuedByONameString;
264 public static String pinnedDomainSslIssuedByUNameString;
265 public static Date pinnedDomainSslStartDate;
266 public static Date pinnedDomainSslEndDate;
268 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
269 public final static int UNRECOGNIZED_USER_AGENT = -1;
270 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
271 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
272 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
273 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
274 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
277 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
278 private ActionBar appBar;
280 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
281 private boolean navigatingHistory;
283 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
284 private Bitmap favoriteIconDefaultBitmap;
286 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
287 private DrawerLayout drawerLayout;
289 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
290 private CoordinatorLayout rootCoordinatorLayout;
292 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
293 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
294 private WebView mainWebView;
296 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
297 private FrameLayout fullScreenVideoFrameLayout;
299 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
300 private SwipeRefreshLayout swipeRefreshLayout;
302 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
303 private RelativeLayout urlAppBarRelativeLayout;
305 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
306 private ImageView favoriteIconImageView;
308 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
309 private CookieManager cookieManager;
311 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
312 private final Map<String, String> customHeaders = new HashMap<>();
314 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
315 private boolean javaScriptEnabled;
317 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
318 private boolean firstPartyCookiesEnabled;
320 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
321 private boolean thirdPartyCookiesEnabled;
323 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
324 private boolean domStorageEnabled;
326 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`. It can be removed once the minimum API >= 26.
327 private boolean saveFormDataEnabled;
329 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
330 private boolean nightMode;
332 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
333 private boolean displayWebpageImagesBoolean;
335 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
336 private String homepage;
338 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
339 private String searchURL;
341 // The block list variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
342 private boolean easyListEnabled;
343 private boolean easyPrivacyEnabled;
344 private boolean fanboysAnnoyanceListEnabled;
345 private boolean fanboysSocialBlockingListEnabled;
346 private boolean ultraPrivacyEnabled;
348 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
349 private Runtime privacyBrowserRuntime;
351 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
352 private boolean proxyThroughOrbot;
354 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
355 private boolean incognitoModeEnabled;
357 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
358 private boolean fullScreenBrowsingModeEnabled;
360 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
361 private boolean inFullScreenBrowsingMode;
363 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
364 private boolean hideSystemBarsOnFullscreen;
366 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
367 private boolean translucentNavigationBarOnFullscreen;
369 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
370 private boolean reapplyDomainSettingsOnRestart;
372 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
373 private boolean reapplyAppSettingsOnRestart;
375 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
376 private boolean displayingFullScreenVideo;
378 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
379 private String currentDomainName;
381 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
382 private boolean ignorePinnedSslCertificate;
384 // `orbotStatusBroadcastReciever` is used in `onCreate()` and `onDestroy()`.
385 private BroadcastReceiver orbotStatusBroadcastReceiver;
387 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyAppSettings()`.
388 private boolean waitingForOrbot;
390 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
391 private boolean domainSettingsApplied;
393 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
394 private int displayWebpageImagesInt;
396 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
397 private boolean onTheFlyDisplayImagesSet;
399 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
400 private String waitingForOrbotHTMLString;
402 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
403 private String privateDataDirectoryString;
405 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
406 private LinearLayout findOnPageLinearLayout;
408 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
409 private EditText findOnPageEditText;
411 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
412 private Menu mainMenu;
414 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
415 private ActionBarDrawerToggle drawerToggle;
417 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
418 private Toolbar supportAppBar;
420 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
421 private EditText urlTextBox;
423 // The color spans are used in `onCreate()` and `highlightUrlText()`.
424 private ForegroundColorSpan redColorSpan;
425 private ForegroundColorSpan initialGrayColorSpan;
426 private ForegroundColorSpan finalGrayColorSpan;
428 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
429 private SslErrorHandler sslErrorHandler;
431 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
432 private static HttpAuthHandler httpAuthHandler;
434 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
435 private InputMethodManager inputMethodManager;
437 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
438 private RelativeLayout mainWebViewRelativeLayout;
440 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
441 private boolean urlIsLoading;
443 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
444 private boolean pinnedDomainSslCertificate;
446 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
447 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
449 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
450 private ListView bookmarksListView;
452 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
453 private TextView bookmarksTitleTextView;
455 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
456 private Cursor bookmarksCursor;
458 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
459 private CursorAdapter bookmarksCursorAdapter;
461 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
462 private String oldFolderNameString;
464 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
465 private ValueCallback<Uri[]> fileChooserCallback;
467 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
468 private String downloadUrl;
469 private String downloadContentDisposition;
470 private long downloadContentLength;
472 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
473 private String downloadImageUrl;
475 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
476 private ArrayAdapter<CharSequence> userAgentNamesArray;
477 private String[] userAgentDataArray;
479 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
480 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
481 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
484 // 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.
485 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
486 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
487 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
488 @SuppressWarnings("deprecation")
489 protected void onCreate(Bundle savedInstanceState) {
490 // Get a handle for the shared preferences.
491 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
493 // Get the theme and screenshot preferences.
494 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
495 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
497 // Disable screenshots if not allowed.
498 if (!allowScreenshots) {
499 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
502 // Set the activity theme.
504 setTheme(R.style.PrivacyBrowserDark);
506 setTheme(R.style.PrivacyBrowserLight);
509 // Run the default commands.
510 super.onCreate(savedInstanceState);
512 // Set the content view.
513 setContentView(R.layout.main_drawerlayout);
515 // Get a handle for `inputMethodManager`.
516 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
518 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
519 supportAppBar = findViewById(R.id.app_bar);
520 setSupportActionBar(supportAppBar);
521 appBar = getSupportActionBar();
523 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
524 assert appBar != null;
526 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
527 appBar.setCustomView(R.layout.url_app_bar);
528 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
530 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
531 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
532 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
533 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
535 // Get a handle for `urlTextBox`.
536 urlTextBox = findViewById(R.id.url_edittext);
538 // Remove the formatting from `urlTextBar` when the user is editing the text.
539 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
540 if (hasFocus) { // The user is editing `urlTextBox`.
541 // Remove the highlighting.
542 urlTextBox.getText().removeSpan(redColorSpan);
543 urlTextBox.getText().removeSpan(initialGrayColorSpan);
544 urlTextBox.getText().removeSpan(finalGrayColorSpan);
545 } else { // The user has stopped editing `urlTextBox`.
546 // Reapply the highlighting.
551 // Set the go button on the keyboard to load the URL in `urlTextBox`.
552 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
553 // If the event is a key-down event on the `enter` button, load the URL.
554 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
555 // Load the URL into the mainWebView and consume the event.
557 loadUrlFromTextBox();
558 } catch (UnsupportedEncodingException e) {
561 // If the enter key was pressed, consume the event.
564 // If any other key was pressed, do not consume the event.
569 // Set `waitingForOrbotHTMLString`.
570 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
572 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
573 currentDomainName = "";
574 orbotStatus = "unknown";
575 waitingForOrbot = false;
577 // Create an Orbot status `BroadcastReceiver`.
578 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
580 public void onReceive(Context context, Intent intent) {
581 // Store the content of the status message in `orbotStatus`.
582 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
584 // If we are waiting on Orbot, load the website now that Orbot is connected.
585 if (orbotStatus.equals("ON") && waitingForOrbot) {
586 // Reset `waitingForOrbot`.
587 waitingForOrbot = false;
589 // Load `formattedUrlString
590 loadUrl(formattedUrlString);
595 // Register `orbotStatusBroadcastReceiver` on `this` context.
596 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
598 // Get handles for views that need to be accessed.
599 drawerLayout = findViewById(R.id.drawerlayout);
600 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
601 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
602 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
603 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
604 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
605 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
606 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
607 mainWebView = findViewById(R.id.main_webview);
608 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
609 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
610 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
611 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
612 favoriteIconImageView = findViewById(R.id.favorite_icon);
614 // 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.
616 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
617 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
618 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
619 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
621 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
622 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
623 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
624 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
627 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
628 launchBookmarksActivityFab.setOnClickListener(v -> {
629 // Create an intent to launch the bookmarks activity.
630 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
632 // Include the current folder with the `Intent`.
633 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
636 startActivity(bookmarksIntent);
639 // Set the create new bookmark folder FAB to display an alert dialog.
640 createBookmarkFolderFab.setOnClickListener(v -> {
641 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
642 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
643 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
646 // Set the create new bookmark FAB to display an alert dialog.
647 createBookmarkFab.setOnClickListener(view -> {
648 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
649 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
650 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
653 // Create a double-tap listener to toggle full-screen mode.
654 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
655 // Override `onDoubleTap()`. All other events are handled using the default settings.
657 public boolean onDoubleTap(MotionEvent event) {
658 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
659 // Toggle `inFullScreenBrowsingMode`.
660 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
662 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
663 // Hide the `appBar`.
666 // Hide the banner ad in the free flavor.
667 if (BuildConfig.FLAVOR.contentEquals("free")) {
668 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
669 AdHelper.hideAd(findViewById(R.id.adview));
672 // Modify the system bars.
673 if (hideSystemBarsOnFullscreen) { // Hide everything.
674 // Remove the translucent overlays.
675 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
677 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
678 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
680 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
681 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
682 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
684 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
686 // Set `rootCoordinatorLayout` to fill the whole screen.
687 rootCoordinatorLayout.setFitsSystemWindows(false);
688 } else { // Hide everything except the status and navigation bars.
689 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
690 rootCoordinatorLayout.setFitsSystemWindows(false);
692 // 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.
693 if (translucentNavigationBarOnFullscreen) {
694 // Set the navigation bar to be translucent.
695 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
698 } else { // Switch to normal viewing mode.
699 // Show the `appBar`.
702 // Show the `BannerAd` in the free flavor.
703 if (BuildConfig.FLAVOR.contentEquals("free")) {
704 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
705 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
708 // Remove the translucent navigation bar flag if it is set.
709 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
711 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
712 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
714 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
715 rootCoordinatorLayout.setSystemUiVisibility(0);
717 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
718 rootCoordinatorLayout.setFitsSystemWindows(true);
721 // Consume the double-tap.
723 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
729 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
730 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
731 // Call `performClick()` on the view, which is required for accessibility.
734 // Send the `event` to `gestureDetector`.
735 return gestureDetector.onTouchEvent(event);
738 // Update `findOnPageCountTextView`.
739 mainWebView.setFindListener(new WebView.FindListener() {
740 // Get a handle for `findOnPageCountTextView`.
741 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
744 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
745 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
746 // Set `findOnPageCountTextView` to `0/0`.
747 findOnPageCountTextView.setText(R.string.zero_of_zero);
748 } else if (isDoneCounting) { // There are matches.
749 // `activeMatchOrdinal` is zero-based.
750 int activeMatch = activeMatchOrdinal + 1;
752 // Build the match string.
753 String matchString = activeMatch + "/" + numberOfMatches;
755 // Set `findOnPageCountTextView`.
756 findOnPageCountTextView.setText(matchString);
761 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
762 findOnPageEditText.addTextChangedListener(new TextWatcher() {
764 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
769 public void onTextChanged(CharSequence s, int start, int before, int count) {
774 public void afterTextChanged(Editable s) {
775 // Search for the text in `mainWebView`.
776 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
780 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
781 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
782 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
783 // Hide the soft keyboard. `0` indicates no additional flags.
784 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
786 // Consume the event.
788 } else { // A different key was pressed.
789 // Do not consume the event.
794 // Implement swipe to refresh
795 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
796 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
797 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
799 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
800 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
801 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
803 // Listen for touches on the navigation menu.
804 final NavigationView navigationView = findViewById(R.id.navigationview);
805 navigationView.setNavigationItemSelectedListener(this);
807 // 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.
808 final Menu navigationMenu = navigationView.getMenu();
809 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
810 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
811 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
812 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
814 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
815 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
816 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
818 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
819 currentBookmarksFolder = "";
821 // Load the home folder, which is `""` in the database.
822 loadBookmarksFolder();
824 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
825 // Convert the id from long to int to match the format of the bookmarks database.
826 int databaseID = (int) id;
828 // Get the bookmark cursor for this ID and move it to the first row.
829 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
830 bookmarkCursor.moveToFirst();
832 // Act upon the bookmark according to the type.
833 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
834 // Store the new folder name in `currentBookmarksFolder`.
835 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
837 // Load the new folder.
838 loadBookmarksFolder();
839 } else { // The selected bookmark is not a folder.
840 // Load the bookmark URL.
841 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
843 // Close the bookmarks drawer.
844 drawerLayout.closeDrawer(GravityCompat.END);
847 // Close the `Cursor`.
848 bookmarkCursor.close();
851 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
852 // Convert the database ID from `long` to `int`.
853 int databaseId = (int) id;
855 // Find out if the selected bookmark is a folder.
856 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
859 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
860 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
862 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
863 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
864 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
866 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
867 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
868 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
871 // Consume the event.
875 // The `DrawerListener` is used to update the Navigation Menu.
876 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
878 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
882 public void onDrawerOpened(@NonNull View drawerView) {
886 public void onDrawerClosed(@NonNull View drawerView) {
890 public void onDrawerStateChanged(int newState) {
891 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
892 // Calculate the total blocked requests counter.
893 int totalBlockedRequests = easyListBlockedRequests + easyPrivacyBlockedRequests + fanboysAnnoyanceListBlockedRequests + fanboysSocialBlockingListBlockedRequests +
894 ultraPrivacyBlockedRequests + thirdPartyBlockedRequests;
896 // Update the back, forward, history, and requests menu items.
897 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
898 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
899 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
900 navigationRequestsMenuItem.setTitle(getResources().getString(R.string.requests) + " - " + totalBlockedRequests);
902 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
903 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
905 // Clear the focus from `urlTextBox` if it has it.
906 urlTextBox.clearFocus();
911 // drawerToggle creates the hamburger icon at the start of the AppBar.
912 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
914 // Get a handle for the progress bar.
915 final ProgressBar progressBar = findViewById(R.id.progress_bar);
917 mainWebView.setWebChromeClient(new WebChromeClient() {
918 // Update the progress bar when a page is loading.
920 public void onProgressChanged(WebView view, int progress) {
921 // Inject the night mode CSS if night mode is enabled.
923 // `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
924 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
925 // `border: none` removes all borders, which can also be used to underline text.
926 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
927 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
928 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
929 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
930 // Initialize a `Handler` to display `mainWebView`.
931 Handler displayWebViewHandler = new Handler();
933 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
934 Runnable displayWebViewRunnable = () -> {
935 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
936 if (progressBar.getVisibility() == View.GONE) {
937 mainWebView.setVisibility(View.VISIBLE);
941 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
942 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
946 // Update the progress bar.
947 progressBar.setProgress(progress);
949 // Set the visibility of the progress bar.
950 if (progress < 100) {
951 // Show the progress bar.
952 progressBar.setVisibility(View.VISIBLE);
954 // Hide the progress bar.
955 progressBar.setVisibility(View.GONE);
957 // Display `mainWebView` if night mode is disabled.
958 // 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
959 // currently enabled.
961 mainWebView.setVisibility(View.VISIBLE);
964 //Stop the swipe to refresh indicator if it is running
965 swipeRefreshLayout.setRefreshing(false);
969 // Set the favorite icon when it changes.
971 public void onReceivedIcon(WebView view, Bitmap icon) {
972 // Only update the favorite icon if the website has finished loading.
973 if (progressBar.getVisibility() == View.GONE) {
974 // Save a copy of the favorite icon.
975 favoriteIconBitmap = icon;
977 // Place the favorite icon in the appBar.
978 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
982 // Save a copy of the title when it changes.
984 public void onReceivedTitle(WebView view, String title) {
985 // Save a copy of the title.
986 webViewTitle = title;
989 // Enter full screen video.
991 public void onShowCustomView(View view, CustomViewCallback callback) {
992 // Set the full screen video flag.
993 displayingFullScreenVideo = true;
995 // Pause the ad if this is the free flavor.
996 if (BuildConfig.FLAVOR.contentEquals("free")) {
997 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
998 AdHelper.pauseAd(findViewById(R.id.adview));
1001 // Remove the translucent overlays.
1002 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1004 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1005 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1007 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1008 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1009 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1011 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1013 // Set `rootCoordinatorLayout` to fill the entire screen.
1014 rootCoordinatorLayout.setFitsSystemWindows(false);
1016 // Disable the sliding drawers.
1017 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1019 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1020 fullScreenVideoFrameLayout.addView(view);
1021 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1024 // Exit full screen video.
1026 public void onHideCustomView() {
1027 // Unset the full screen video flag.
1028 displayingFullScreenVideo = true;
1030 // Hide `fullScreenVideoFrameLayout`.
1031 fullScreenVideoFrameLayout.removeAllViews();
1032 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1034 // Enable the sliding drawers.
1035 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1037 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1038 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1039 if (hideSystemBarsOnFullscreen) { // Hide everything.
1040 // Remove the translucent navigation setting if it is currently flagged.
1041 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1043 // Remove the translucent status bar overlay.
1044 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1046 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1047 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1049 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1050 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1051 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1053 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1054 } else { // Hide everything except the status and navigation bars.
1055 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1056 rootCoordinatorLayout.setSystemUiVisibility(0);
1058 // Add the translucent status flag if it is unset.
1059 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1061 if (translucentNavigationBarOnFullscreen) {
1062 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1063 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1065 // Set the navigation bar to be black.
1066 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1069 } else { // Switch to normal viewing mode.
1070 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1071 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1075 // Show the `BannerAd` in the free flavor.
1076 if (BuildConfig.FLAVOR.contentEquals("free")) {
1077 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1078 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1081 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1082 rootCoordinatorLayout.setSystemUiVisibility(0);
1084 // Remove the translucent navigation bar flag if it is set.
1085 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1087 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1088 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1090 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1091 rootCoordinatorLayout.setFitsSystemWindows(true);
1094 // Show the ad if this is the free flavor.
1095 if (BuildConfig.FLAVOR.contentEquals("free")) {
1096 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1097 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1103 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1104 // Show the file chooser if the device is running API >= 21.
1105 if (Build.VERSION.SDK_INT >= 21) {
1106 // Store the file path callback.
1107 fileChooserCallback = filePathCallback;
1109 // Create an intent to open a chooser based ont the file chooser parameters.
1110 Intent fileChooserIntent = fileChooserParams.createIntent();
1112 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1113 startActivityForResult(fileChooserIntent, 0);
1119 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1120 registerForContextMenu(mainWebView);
1122 // Allow the downloading of files.
1123 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1124 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1125 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1126 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1128 // Store the variables for future use by `onRequestPermissionsResult()`.
1130 downloadContentDisposition = contentDisposition;
1131 downloadContentLength = contentLength;
1133 // Show a dialog if the user has previously denied the permission.
1134 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1135 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1136 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1138 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1139 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1140 } else { // Show the permission request directly.
1141 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1142 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1144 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1145 // Get a handle for the download file alert dialog.
1146 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1148 // Show the download file alert dialog.
1149 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1153 // Allow pinch to zoom.
1154 mainWebView.getSettings().setBuiltInZoomControls(true);
1156 // Hide zoom controls.
1157 mainWebView.getSettings().setDisplayZoomControls(false);
1159 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1160 mainWebView.getSettings().setUseWideViewPort(true);
1162 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1163 mainWebView.getSettings().setLoadWithOverviewMode(true);
1165 // Explicitly disable geolocation.
1166 mainWebView.getSettings().setGeolocationEnabled(false);
1168 // Initialize cookieManager.
1169 cookieManager = CookieManager.getInstance();
1171 // 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).
1172 customHeaders.put("X-Requested-With", "");
1174 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1175 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1177 // Get the intent that started the app.
1178 final Intent launchingIntent = getIntent();
1180 // Extract the launching intent data as `launchingIntentUriData`.
1181 final Uri launchingIntentUriData = launchingIntent.getData();
1183 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1184 if (launchingIntentUriData != null) {
1185 formattedUrlString = launchingIntentUriData.toString();
1188 // Get a handle for the `Runtime`.
1189 privacyBrowserRuntime = Runtime.getRuntime();
1191 // Store the application's private data directory.
1192 privateDataDirectoryString = getApplicationInfo().dataDir;
1193 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1195 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1196 inFullScreenBrowsingMode = false;
1198 // Initialize the privacy settings variables.
1199 javaScriptEnabled = false;
1200 firstPartyCookiesEnabled = false;
1201 thirdPartyCookiesEnabled = false;
1202 domStorageEnabled = false;
1203 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1206 // Initialize the WebView title.
1207 webViewTitle = getString(R.string.no_title);
1209 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1210 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1211 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1212 assert favoriteIconBitmapDrawable != null;
1213 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1215 // If the favorite icon is null, load the default.
1216 if (favoriteIconBitmap == null) {
1217 favoriteIconBitmap = favoriteIconDefaultBitmap;
1220 // Initialize the user agent array adapter and string array.
1221 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1222 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1224 // Apply the app settings from the shared preferences.
1227 // Instantiate the block list helper.
1228 BlockListHelper blockListHelper = new BlockListHelper();
1230 // Initialize the list of resource requests.
1231 resourceRequests = new ArrayList<>();
1233 // Parse the block lists.
1234 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1235 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1236 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1237 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1238 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1240 // Store the list versions.
1241 easyListVersion = easyList.get(0).get(0)[0];
1242 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1243 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1244 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1245 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1247 mainWebView.setWebViewClient(new WebViewClient() {
1248 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1249 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1250 @SuppressWarnings("deprecation")
1252 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1253 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1254 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1255 formattedUrlString = "";
1257 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1258 applyDomainSettings(url, true, false);
1260 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1262 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1263 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1264 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1266 // Parse the url and set it as the data for the intent.
1267 emailIntent.setData(Uri.parse(url));
1269 // Open the email program in a new task instead of as part of Privacy Browser.
1270 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1273 startActivity(emailIntent);
1275 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1277 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1278 // Open the dialer and load the phone number, but wait for the user to place the call.
1279 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1281 // Add the phone number to the intent.
1282 dialIntent.setData(Uri.parse(url));
1284 // Open the dialer in a new task instead of as part of Privacy Browser.
1285 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1288 startActivity(dialIntent);
1290 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1292 } else { // Load a system chooser to select an app that can handle the URL.
1293 // Open an app that can handle the URL.
1294 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1296 // Add the URL to the intent.
1297 genericIntent.setData(Uri.parse(url));
1299 // List all apps that can handle the URL instead of just opening the first one.
1300 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1302 // Open the app in a new task instead of as part of Privacy Browser.
1303 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1305 // Start the app or display a snackbar if no app is available to handle the URL.
1307 startActivity(genericIntent);
1308 } catch (ActivityNotFoundException exception) {
1309 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1312 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1317 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1318 @SuppressWarnings("deprecation")
1320 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1321 // Create an empty web resource response to be used if the resource request is blocked.
1322 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1324 // Reset the whitelist results tracker.
1325 whiteListResultStringArray = null;
1327 // Initialize the third party request tracker.
1328 boolean isThirdPartyRequest = false;
1330 // Initialize the current domain string.
1331 String currentDomain = "";
1333 // Nobody is happy when comparing null strings.
1334 if (!(formattedUrlString == null) && !(url == null)) {
1335 // Get the domain strings to URIs.
1336 Uri currentDomainUri = Uri.parse(formattedUrlString);
1337 Uri requestDomainUri = Uri.parse(url);
1339 // Get the domain host names.
1340 String currentBaseDomain = currentDomainUri.getHost();
1341 String requestBaseDomain = requestDomainUri.getHost();
1343 // Update the current domain variable.
1344 currentDomain = currentBaseDomain;
1346 // Only compare the current base domain and the request base domain if neither is null.
1347 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1348 // Determine the current base domain.
1349 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1350 // Remove the first subdomain.
1351 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1354 // Determine the request base domain.
1355 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1356 // Remove the first subdomain.
1357 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1360 // Update the third party request tracker.
1361 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1365 // Block third-party requests if enabled.
1366 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1367 // Increment the third-party blocked requests counter.
1368 thirdPartyBlockedRequests++;
1370 // Add the request to the log.
1371 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1373 // Return an empty web resource response.
1374 return emptyWebResourceResponse;
1377 // Check UltraPrivacy if it is enabled.
1378 if (ultraPrivacyEnabled) {
1379 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1380 // Increment the UltraPrivacy blocked requests counter.
1381 ultraPrivacyBlockedRequests++;
1383 // The resource request was blocked. Return an empty web resource response.
1384 return emptyWebResourceResponse;
1387 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1388 if (whiteListResultStringArray != null) {
1389 // Add a whitelist entry to the resource requests array.
1390 resourceRequests.add(whiteListResultStringArray);
1392 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1397 // Check EasyList if it is enabled.
1398 if (easyListEnabled) {
1399 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1400 // Increment the EasyList blocked requests counter.
1401 easyListBlockedRequests++;
1403 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1404 whiteListResultStringArray = null;
1406 // The resource request was blocked. Return an empty web resource response.
1407 return emptyWebResourceResponse;
1411 // Check EasyPrivacy if it is enabled.
1412 if (easyPrivacyEnabled) {
1413 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1414 // Increment the EasyPrivacy blocked requests counter.
1415 easyPrivacyBlockedRequests++;
1417 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1418 whiteListResultStringArray = null;
1420 // The resource request was blocked. Return an empty web resource response.
1421 return emptyWebResourceResponse;
1425 // Check Fanboy’s Annoyance List if it is enabled.
1426 if (fanboysAnnoyanceListEnabled) {
1427 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1428 // Increment the Fanboy's Annoyance List blocked requests counter.
1429 fanboysAnnoyanceListBlockedRequests++;
1431 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1432 whiteListResultStringArray = null;
1434 // The resource request was blocked. Return an empty web resource response.
1435 return emptyWebResourceResponse;
1437 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1438 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1439 // Increment the Fanboy's Social Blocking List blocked requests counter.
1440 fanboysSocialBlockingListBlockedRequests++;
1442 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1443 whiteListResultStringArray = null;
1445 // The resource request was blocked. Return an empty web resource response.
1446 return emptyWebResourceResponse;
1450 // Add the request to the log because it hasn't been processed by any of the previous checks.
1451 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1452 resourceRequests.add(whiteListResultStringArray);
1453 } else { // The request didn't match any blocklist entry. Log it as a defult request.
1454 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1457 // The resource request has not been blocked. `return null` loads the requested resource.
1461 // Handle HTTP authentication requests.
1463 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1464 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1465 httpAuthHandler = handler;
1467 // Display the HTTP authentication dialog.
1468 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1469 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1472 // Update the URL in urlTextBox when the page starts to load.
1474 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1475 // Reset the list of resource requests.
1476 resourceRequests.clear();
1478 // Initialize the counters for requests blocked by each blocklist.
1479 easyListBlockedRequests = 0;
1480 easyPrivacyBlockedRequests = 0;
1481 fanboysAnnoyanceListBlockedRequests = 0;
1482 fanboysSocialBlockingListBlockedRequests = 0;
1483 ultraPrivacyBlockedRequests = 0;
1484 thirdPartyBlockedRequests = 0;
1486 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1488 mainWebView.setVisibility(View.INVISIBLE);
1491 // Hide the keyboard. `0` indicates no additional flags.
1492 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1494 // Check to see if Privacy Browser is waiting on Orbot.
1495 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1496 // 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.
1497 formattedUrlString = url;
1499 // Display the formatted URL text.
1500 urlTextBox.setText(formattedUrlString);
1502 // Apply text highlighting to `urlTextBox`.
1505 // Apply any custom domain settings if the URL was loaded by navigating history.
1506 if (navigatingHistory) {
1507 // Reset `navigatingHistory`.
1508 navigatingHistory = false;
1510 // Apply the domain settings.
1511 applyDomainSettings(url, true, false);
1514 // 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.
1515 urlIsLoading = true;
1519 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1521 public void onPageFinished(WebView view, String url) {
1522 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1523 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1524 cookieManager.flush();
1527 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1528 urlIsLoading = false;
1530 // Clear the cache and history if Incognito Mode is enabled.
1531 if (incognitoModeEnabled) {
1532 // Clear the cache. `true` includes disk files.
1533 mainWebView.clearCache(true);
1535 // Clear the back/forward history.
1536 mainWebView.clearHistory();
1538 // Manually delete cache folders.
1540 // Delete the main cache directory.
1541 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1543 // Delete the secondary `Service Worker` cache directory.
1544 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1545 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1546 } catch (IOException e) {
1547 // Do nothing if an error is thrown.
1551 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1552 if (!waitingForOrbot) {
1553 // Check to see if `WebView` has set `url` to be `about:blank`.
1554 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1555 // Set `formattedUrlString` to `""`.
1556 formattedUrlString = "";
1558 urlTextBox.setText(formattedUrlString);
1560 // Request focus for `urlTextBox`.
1561 urlTextBox.requestFocus();
1563 // Display the keyboard.
1564 inputMethodManager.showSoftInput(urlTextBox, 0);
1566 // Apply the domain settings. This clears any settings from the previous domain.
1567 applyDomainSettings(formattedUrlString, true, false);
1568 } else { // `WebView` has loaded a webpage.
1569 // Set `formattedUrlString`.
1570 formattedUrlString = url;
1572 // Only update `urlTextBox` if the user is not typing in it.
1573 if (!urlTextBox.hasFocus()) {
1574 // Display the formatted URL text.
1575 urlTextBox.setText(formattedUrlString);
1577 // Apply text highlighting to `urlTextBox`.
1582 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1583 sslCertificate = mainWebView.getCertificate();
1585 // 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.
1586 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1587 // Initialize the current SSL certificate variables.
1588 String currentWebsiteIssuedToCName = "";
1589 String currentWebsiteIssuedToOName = "";
1590 String currentWebsiteIssuedToUName = "";
1591 String currentWebsiteIssuedByCName = "";
1592 String currentWebsiteIssuedByOName = "";
1593 String currentWebsiteIssuedByUName = "";
1594 Date currentWebsiteSslStartDate = null;
1595 Date currentWebsiteSslEndDate = null;
1598 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1599 if (sslCertificate != null) {
1600 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1601 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1602 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1603 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1604 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1605 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1606 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1607 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1610 // 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`.
1611 String currentWebsiteSslStartDateString = "";
1612 String currentWebsiteSslEndDateString = "";
1613 String pinnedDomainSslStartDateString = "";
1614 String pinnedDomainSslEndDateString = "";
1616 // Convert the `Dates` to `Strings` if they are not `null`.
1617 if (currentWebsiteSslStartDate != null) {
1618 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1621 if (currentWebsiteSslEndDate != null) {
1622 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1625 if (pinnedDomainSslStartDate != null) {
1626 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1629 if (pinnedDomainSslEndDate != null) {
1630 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1633 // Check to see if the pinned SSL certificate matches the current website certificate.
1634 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1635 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1636 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1637 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1638 // The pinned SSL certificate doesn't match the current domain certificate.
1639 //Display the pinned SSL certificate mismatch `AlertDialog`.
1640 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1641 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1647 // Handle SSL Certificate errors.
1649 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1650 // Get the current website SSL certificate.
1651 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1653 // Extract the individual pieces of information from the current website SSL certificate.
1654 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1655 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1656 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1657 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1658 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1659 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1660 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1661 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1663 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1664 if (pinnedDomainSslCertificate &&
1665 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1666 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1667 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1668 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1669 // An SSL certificate is pinned and matches the current domain certificate.
1670 // Proceed to the website without displaying an error.
1672 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1673 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1674 sslErrorHandler = handler;
1676 // Display the SSL error `AlertDialog`.
1677 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1678 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1683 // Load the website if not waiting for Orbot to connect.
1684 if (!waitingForOrbot) {
1685 loadUrl(formattedUrlString);
1690 protected void onNewIntent(Intent intent) {
1691 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1694 // Check to see if the intent contains a new URL.
1695 if (intent.getData() != null) {
1696 // Get the intent data.
1697 final Uri intentUriData = intent.getData();
1699 // Load the website.
1700 loadUrl(intentUriData.toString());
1702 // Close the navigation drawer if it is open.
1703 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1704 drawerLayout.closeDrawer(GravityCompat.START);
1707 // Close the bookmarks drawer if it is open.
1708 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1709 drawerLayout.closeDrawer(GravityCompat.END);
1712 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1713 mainWebView.requestFocus();
1718 public void onRestart() {
1719 // Run the default commands.
1722 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1723 if (proxyThroughOrbot) {
1724 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1725 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1727 // Send the intent to the Orbot package.
1728 orbotIntent.setPackage("org.torproject.android");
1731 sendBroadcast(orbotIntent);
1734 // Apply the app settings if returning from the Settings activity..
1735 if (reapplyAppSettingsOnRestart) {
1736 // Apply the app settings.
1739 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1740 if (reloadOnRestart) {
1741 // Reload `mainWebView`.
1742 mainWebView.reload();
1744 // Reset `reloadOnRestartBoolean`.
1745 reloadOnRestart = false;
1748 // Reset the return from settings flag.
1749 reapplyAppSettingsOnRestart = false;
1752 // Apply the domain settings if returning from the Domains activity.
1753 if (reapplyDomainSettingsOnRestart) {
1754 // Reapply the domain settings.
1755 applyDomainSettings(formattedUrlString, false, true);
1757 // Reset `reapplyDomainSettingsOnRestart`.
1758 reapplyDomainSettingsOnRestart = false;
1761 // Load the URL on restart to apply changes to night mode.
1762 if (loadUrlOnRestart) {
1763 // Load the current `formattedUrlString`.
1764 loadUrl(formattedUrlString);
1766 // Reset `loadUrlOnRestart.
1767 loadUrlOnRestart = false;
1770 // Update the bookmarks drawer if returning from the Bookmarks activity.
1771 if (restartFromBookmarksActivity) {
1772 // Close the bookmarks drawer.
1773 drawerLayout.closeDrawer(GravityCompat.END);
1775 // Reload the bookmarks drawer.
1776 loadBookmarksFolder();
1778 // Reset `restartFromBookmarksActivity`.
1779 restartFromBookmarksActivity = false;
1782 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1783 updatePrivacyIcons(true);
1786 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1788 public void onResume() {
1789 // Run the default commands.
1792 // Resume JavaScript (if enabled).
1793 mainWebView.resumeTimers();
1795 // Resume `mainWebView`.
1796 mainWebView.onResume();
1798 // Resume the adView for the free flavor.
1799 if (BuildConfig.FLAVOR.contentEquals("free")) {
1801 AdHelper.resumeAd(findViewById(R.id.adview));
1804 // Display a message to the user if waiting for Orbot.
1805 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1806 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1807 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1810 if (displayingFullScreenVideo) {
1811 // Remove the translucent overlays.
1812 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1814 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1815 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1817 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1818 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1819 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1821 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1826 public void onPause() {
1827 // Run the default commands.
1830 // Pause `mainWebView`.
1831 mainWebView.onPause();
1833 // Stop all JavaScript.
1834 mainWebView.pauseTimers();
1836 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1837 if (BuildConfig.FLAVOR.contentEquals("free")) {
1839 AdHelper.pauseAd(findViewById(R.id.adview));
1844 public void onDestroy() {
1845 // Unregister the Orbot status broadcast receiver.
1846 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1848 // Run the default commands.
1853 public boolean onCreateOptionsMenu(Menu menu) {
1854 // Inflate the menu; this adds items to the action bar if it is present.
1855 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1857 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1860 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1861 updatePrivacyIcons(false);
1863 // Get handles for the menu items.
1864 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1865 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1866 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1867 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1868 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1869 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1870 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1872 // Only display third-party cookies if API >= 21
1873 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1875 // Only display the form data menu items if the API < 26.
1876 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1877 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1879 // Only show Ad Consent if this is the free flavor.
1880 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1882 // Get the shared preference values. `this` references the current context.
1883 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1885 // 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.
1886 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1887 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1888 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1889 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1890 } else { //Do not display the additional icons.
1891 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1892 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1893 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1900 public boolean onPrepareOptionsMenu(Menu menu) {
1901 // Get handles for the menu items.
1902 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1903 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1904 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1905 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1906 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1907 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1908 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1909 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1910 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1911 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1912 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1913 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1914 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1915 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1916 MenuItem blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1917 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1918 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1919 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1921 // Set the text for the domain menu item.
1922 if (domainSettingsApplied) {
1923 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1925 addOrEditDomain.setTitle(R.string.add_domain_settings);
1928 // Set the status of the menu item checkboxes.
1929 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1930 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1931 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1932 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
1933 easyListMenuItem.setChecked(easyListEnabled);
1934 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1935 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1936 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1937 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
1938 blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1939 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1940 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1942 // Enable third-party cookies if first-party cookies are enabled.
1943 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1945 // Enable DOM Storage if JavaScript is enabled.
1946 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1948 // Enable Clear Cookies if there are any.
1949 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1951 // Get a count of the number of files in the Local Storage directory.
1952 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1953 int localStorageDirectoryNumberOfFiles = 0;
1954 if (localStorageDirectory.exists()) {
1955 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1958 // Get a count of the number of files in the IndexedDB directory.
1959 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1960 int indexedDBDirectoryNumberOfFiles = 0;
1961 if (indexedDBDirectory.exists()) {
1962 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1965 // Enable Clear DOM Storage if there is any.
1966 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1968 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1969 if (Build.VERSION.SDK_INT < 26) {
1970 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1971 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1973 // Disable clear form data because it is not supported on current version of Android.
1974 clearFormDataMenuItem.setEnabled(false);
1977 // Enable Clear Data if any of the submenu items are enabled.
1978 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1980 // Update the display names for the blocklists with the number of blocked requests.
1981 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1982 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1983 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1984 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1985 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1986 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1988 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
1989 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1991 // Initialize font size variables.
1992 int fontSize = mainWebView.getSettings().getTextZoom();
1993 String fontSizeTitle;
1994 MenuItem selectedFontSizeMenuItem;
1996 // Prepare the font size title and current size menu item.
1999 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2000 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2004 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2005 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2009 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2010 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2014 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2015 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2019 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2020 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2024 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2025 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2029 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2030 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2034 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2035 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2039 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2040 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2044 // Set the font size title and select the current size menu item.
2045 fontSizeMenuItem.setTitle(fontSizeTitle);
2046 selectedFontSizeMenuItem.setChecked(true);
2048 // Run all the other default commands.
2049 super.onPrepareOptionsMenu(menu);
2051 // Display the menu.
2056 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2057 @SuppressLint("SetJavaScriptEnabled")
2058 // removeAllCookies is deprecated, but it is required for API < 21.
2059 @SuppressWarnings("deprecation")
2060 public boolean onOptionsItemSelected(MenuItem menuItem) {
2061 // Get the selected menu item ID.
2062 int menuItemId = menuItem.getItemId();
2064 // Set the commands that relate to the menu entries.
2065 switch (menuItemId) {
2066 case R.id.toggle_javascript:
2067 // Switch the status of javaScriptEnabled.
2068 javaScriptEnabled = !javaScriptEnabled;
2070 // Apply the new JavaScript status.
2071 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2073 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2074 updatePrivacyIcons(true);
2076 // Display a `Snackbar`.
2077 if (javaScriptEnabled) { // JavaScrip is enabled.
2078 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2079 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2080 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2081 } else { // Privacy mode.
2082 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2085 // Reload the WebView.
2086 mainWebView.reload();
2089 case R.id.add_or_edit_domain:
2090 if (domainSettingsApplied) { // Edit the current domain settings.
2091 // Reapply the domain settings on returning to `MainWebViewActivity`.
2092 reapplyDomainSettingsOnRestart = true;
2093 currentDomainName = "";
2095 // Create an intent to launch the domains activity.
2096 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2098 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2099 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2100 domainsIntent.putExtra("closeOnBack", true);
2103 startActivity(domainsIntent);
2104 } else { // Add a new domain.
2105 // Apply the new domain settings on returning to `MainWebViewActivity`.
2106 reapplyDomainSettingsOnRestart = true;
2107 currentDomainName = "";
2109 // Get the current domain
2110 Uri currentUri = Uri.parse(formattedUrlString);
2111 String currentDomain = currentUri.getHost();
2113 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2114 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2116 // Create the domain and store the database ID.
2117 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2119 // Create an intent to launch the domains activity.
2120 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2122 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2123 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2124 domainsIntent.putExtra("closeOnBack", true);
2127 startActivity(domainsIntent);
2131 case R.id.toggle_first_party_cookies:
2132 // Switch the status of firstPartyCookiesEnabled.
2133 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2135 // Update the menu checkbox.
2136 menuItem.setChecked(firstPartyCookiesEnabled);
2138 // Apply the new cookie status.
2139 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2141 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2142 updatePrivacyIcons(true);
2144 // Display a `Snackbar`.
2145 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2146 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2147 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2148 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2149 } else { // Privacy mode.
2150 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2153 // Reload the WebView.
2154 mainWebView.reload();
2157 case R.id.toggle_third_party_cookies:
2158 if (Build.VERSION.SDK_INT >= 21) {
2159 // Switch the status of thirdPartyCookiesEnabled.
2160 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2162 // Update the menu checkbox.
2163 menuItem.setChecked(thirdPartyCookiesEnabled);
2165 // Apply the new cookie status.
2166 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2168 // Display a `Snackbar`.
2169 if (thirdPartyCookiesEnabled) {
2170 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2172 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2175 // Reload the WebView.
2176 mainWebView.reload();
2177 } // Else do nothing because SDK < 21.
2180 case R.id.toggle_dom_storage:
2181 // Switch the status of domStorageEnabled.
2182 domStorageEnabled = !domStorageEnabled;
2184 // Update the menu checkbox.
2185 menuItem.setChecked(domStorageEnabled);
2187 // Apply the new DOM Storage status.
2188 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2190 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2191 updatePrivacyIcons(true);
2193 // Display a `Snackbar`.
2194 if (domStorageEnabled) {
2195 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2197 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2200 // Reload the WebView.
2201 mainWebView.reload();
2204 // Form data can be removed once the minimum API >= 26.
2205 case R.id.toggle_save_form_data:
2206 // Switch the status of saveFormDataEnabled.
2207 saveFormDataEnabled = !saveFormDataEnabled;
2209 // Update the menu checkbox.
2210 menuItem.setChecked(saveFormDataEnabled);
2212 // Apply the new form data status.
2213 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2215 // Display a `Snackbar`.
2216 if (saveFormDataEnabled) {
2217 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2219 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2222 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2223 updatePrivacyIcons(true);
2225 // Reload the WebView.
2226 mainWebView.reload();
2229 case R.id.clear_cookies:
2230 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2231 .setAction(R.string.undo, v -> {
2232 // Do nothing because everything will be handled by `onDismissed()` below.
2234 .addCallback(new Snackbar.Callback() {
2236 public void onDismissed(Snackbar snackbar, int event) {
2238 // The user pushed the `Undo` button.
2239 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2243 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2245 // `cookieManager.removeAllCookie()` varies by SDK.
2246 if (Build.VERSION.SDK_INT < 21) {
2247 cookieManager.removeAllCookie();
2249 // `null` indicates no callback.
2250 cookieManager.removeAllCookies(null);
2258 case R.id.clear_dom_storage:
2259 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2260 .setAction(R.string.undo, v -> {
2261 // Do nothing because everything will be handled by `onDismissed()` below.
2263 .addCallback(new Snackbar.Callback() {
2265 public void onDismissed(Snackbar snackbar, int event) {
2267 // The user pushed the `Undo` button.
2268 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2272 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2274 // Delete the DOM Storage.
2275 WebStorage webStorage = WebStorage.getInstance();
2276 webStorage.deleteAllData();
2278 // Manually delete the DOM storage files and directories.
2280 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2281 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2283 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2284 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2285 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2286 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2287 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2288 } catch (IOException e) {
2289 // Do nothing if an error is thrown.
2297 // Form data can be remove once the minimum API >= 26.
2298 case R.id.clear_form_data:
2299 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2300 .setAction(R.string.undo, v -> {
2301 // Do nothing because everything will be handled by `onDismissed()` below.
2303 .addCallback(new Snackbar.Callback() {
2305 public void onDismissed(Snackbar snackbar, int event) {
2307 // The user pushed the `Undo` button.
2308 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2312 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2314 // Delete the form data.
2315 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2316 mainWebViewDatabase.clearFormData();
2323 case R.id.font_size_twenty_five_percent:
2324 mainWebView.getSettings().setTextZoom(25);
2327 case R.id.font_size_fifty_percent:
2328 mainWebView.getSettings().setTextZoom(50);
2331 case R.id.font_size_seventy_five_percent:
2332 mainWebView.getSettings().setTextZoom(75);
2335 case R.id.font_size_one_hundred_percent:
2336 mainWebView.getSettings().setTextZoom(100);
2339 case R.id.font_size_one_hundred_twenty_five_percent:
2340 mainWebView.getSettings().setTextZoom(125);
2343 case R.id.font_size_one_hundred_fifty_percent:
2344 mainWebView.getSettings().setTextZoom(150);
2347 case R.id.font_size_one_hundred_seventy_five_percent:
2348 mainWebView.getSettings().setTextZoom(175);
2351 case R.id.font_size_two_hundred_percent:
2352 mainWebView.getSettings().setTextZoom(200);
2355 case R.id.swipe_to_refresh:
2356 // Toggle swipe to refresh.
2357 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2360 case R.id.display_images:
2361 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2362 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2363 mainWebView.reload();
2364 } else { // Images are not currently loaded automatically.
2365 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2368 // Set `onTheFlyDisplayImagesSet`.
2369 onTheFlyDisplayImagesSet = true;
2372 case R.id.view_source:
2373 // Launch the View Source activity.
2374 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2375 startActivity(viewSourceIntent);
2379 // Toggle the EasyList status.
2380 easyListEnabled = !easyListEnabled;
2382 // Update the menu checkbox.
2383 menuItem.setChecked(easyListEnabled);
2385 // Reload the main WebView.
2386 mainWebView.reload();
2389 case R.id.easyprivacy:
2390 // Toggle the EasyPrivacy status.
2391 easyPrivacyEnabled = !easyPrivacyEnabled;
2393 // Update the menu checkbox.
2394 menuItem.setChecked(easyPrivacyEnabled);
2396 // Reload the main WebView.
2397 mainWebView.reload();
2400 case R.id.fanboys_annoyance_list:
2401 // Toggle Fanboy's Annoyance List status.
2402 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2404 // Update the menu checkbox.
2405 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2407 // Update the staus of Fanboy's Social Blocking List.
2408 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2409 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2411 // Reload the main WebView.
2412 mainWebView.reload();
2415 case R.id.fanboys_social_blocking_list:
2416 // Toggle Fanboy's Social Blocking List status.
2417 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2419 // Update the menu checkbox.
2420 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2422 // Reload the main WebView.
2423 mainWebView.reload();
2426 case R.id.ultraprivacy:
2427 // Toggle the UltraPrivacy status.
2428 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2430 // Update the menu checkbox.
2431 menuItem.setChecked(ultraPrivacyEnabled);
2433 // Reload the main WebView.
2434 mainWebView.reload();
2437 case R.id.block_all_third_party_requests:
2438 //Toggle the third-party requests blocker status.
2439 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2441 // Update the menu checkbox.
2442 menuItem.setChecked(blockAllThirdPartyRequests);
2444 // Reload the main WebView.
2445 mainWebView.reload();
2449 // Setup the share string.
2450 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2452 // Create the share intent.
2453 Intent shareIntent = new Intent();
2454 shareIntent.setAction(Intent.ACTION_SEND);
2455 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2456 shareIntent.setType("text/plain");
2459 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2462 case R.id.find_on_page:
2463 // Hide the URL app bar.
2464 supportAppBar.setVisibility(View.GONE);
2466 // Show the Find on Page `RelativeLayout`.
2467 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2469 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2470 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2471 findOnPageEditText.postDelayed(() -> {
2472 // Set the focus on `findOnPageEditText`.
2473 findOnPageEditText.requestFocus();
2475 // Display the keyboard. `0` sets no input flags.
2476 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2481 // Get a `PrintManager` instance.
2482 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2484 // Convert `mainWebView` to `printDocumentAdapter`.
2485 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2487 // Remove the lint error below that `printManager` might be `null`.
2488 assert printManager != null;
2490 // Print the document. The print attributes are `null`.
2491 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2494 case R.id.add_to_homescreen:
2495 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2496 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2497 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2499 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2503 mainWebView.reload();
2506 case R.id.ad_consent:
2507 // Display the ad consent dialog.
2508 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2509 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2513 // Don't consume the event.
2514 return super.onOptionsItemSelected(menuItem);
2518 // removeAllCookies is deprecated, but it is required for API < 21.
2519 @SuppressWarnings("deprecation")
2521 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2522 int menuItemId = menuItem.getItemId();
2524 switch (menuItemId) {
2530 if (mainWebView.canGoBack()) {
2531 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2532 formattedUrlString = "";
2534 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2535 navigatingHistory = true;
2537 // Load the previous website in the history.
2538 mainWebView.goBack();
2543 if (mainWebView.canGoForward()) {
2544 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2545 formattedUrlString = "";
2547 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2548 navigatingHistory = true;
2550 // Load the next website in the history.
2551 mainWebView.goForward();
2556 // Get the `WebBackForwardList`.
2557 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2559 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2560 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2561 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2565 // Launch the requests activity.
2566 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2567 startActivity(requestsIntent);
2570 case R.id.downloads:
2571 // Launch the system Download Manager.
2572 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2574 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2575 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2577 startActivity(downloadManagerIntent);
2581 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2582 reapplyDomainSettingsOnRestart = true;
2583 currentDomainName = "";
2585 // Launch the domains activity.
2586 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2587 startActivity(domainsIntent);
2591 // Set the flag to reapply app settings on restart when returning from Settings.
2592 reapplyAppSettingsOnRestart = true;
2594 // Set the flag to reapply the domain settings on restart when returning from Settings.
2595 reapplyDomainSettingsOnRestart = true;
2596 currentDomainName = "";
2598 // Launch the settings activity.
2599 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2600 startActivity(settingsIntent);
2604 // Launch `GuideActivity`.
2605 Intent guideIntent = new Intent(this, GuideActivity.class);
2606 startActivity(guideIntent);
2610 // Launch `AboutActivity`.
2611 Intent aboutIntent = new Intent(this, AboutActivity.class);
2612 startActivity(aboutIntent);
2615 case R.id.clearAndExit:
2616 // Get a handle for `sharedPreferences`. `this` references the current context.
2617 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2619 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2622 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2623 // The command to remove cookies changed slightly in API 21.
2624 if (Build.VERSION.SDK_INT >= 21) {
2625 cookieManager.removeAllCookies(null);
2627 cookieManager.removeAllCookie();
2630 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2632 // We have to use two commands because `Runtime.exec()` does not like `*`.
2633 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2634 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2635 } catch (IOException e) {
2636 // Do nothing if an error is thrown.
2640 // Clear DOM storage.
2641 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2642 // Ask `WebStorage` to clear the DOM storage.
2643 WebStorage webStorage = WebStorage.getInstance();
2644 webStorage.deleteAllData();
2646 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2648 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2649 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2651 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2652 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2653 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2654 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2655 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2656 } catch (IOException e) {
2657 // Do nothing if an error is thrown.
2661 // Clear form data if the API < 26.
2662 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2663 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2664 webViewDatabase.clearFormData();
2666 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2668 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2669 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2670 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2671 } catch (IOException e) {
2672 // Do nothing if an error is thrown.
2677 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2678 // `true` includes disk files.
2679 mainWebView.clearCache(true);
2681 // Manually delete the cache directories.
2683 // Delete the main cache directory.
2684 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2686 // Delete the secondary `Service Worker` cache directory.
2687 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2688 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2689 } catch (IOException e) {
2690 // Do nothing if an error is thrown.
2694 // Clear SSL certificate preferences.
2695 mainWebView.clearSslPreferences();
2697 // Clear the back/forward history.
2698 mainWebView.clearHistory();
2700 // Clear `formattedUrlString`.
2701 formattedUrlString = null;
2703 // Clear `customHeaders`.
2704 customHeaders.clear();
2706 // Detach all views from `mainWebViewRelativeLayout`.
2707 mainWebViewRelativeLayout.removeAllViews();
2709 // Destroy the internal state of `mainWebView`.
2710 mainWebView.destroy();
2712 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2713 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2714 if (clearEverything) {
2716 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2717 } catch (IOException e) {
2718 // Do nothing if an error is thrown.
2722 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2723 if (Build.VERSION.SDK_INT >= 21) {
2724 finishAndRemoveTask();
2729 // Remove the terminated program from RAM. The status code is `0`.
2734 // Close the navigation drawer.
2735 drawerLayout.closeDrawer(GravityCompat.START);
2740 public void onPostCreate(Bundle savedInstanceState) {
2741 super.onPostCreate(savedInstanceState);
2743 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2744 drawerToggle.syncState();
2748 public void onConfigurationChanged(Configuration newConfig) {
2749 super.onConfigurationChanged(newConfig);
2751 // Reload the ad for the free flavor if we not in full screen mode.
2752 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2753 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2754 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2757 // `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:
2758 // https://code.google.com/p/android/issues/detail?id=20493#c8
2759 // ActivityCompat.invalidateOptionsMenu(this);
2763 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2764 // Store the `HitTestResult`.
2765 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2768 final String imageUrl;
2769 final String linkUrl;
2771 // Get a handle for the `ClipboardManager`.
2772 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2774 // Remove the lint errors below that `clipboardManager` might be `null`.
2775 assert clipboardManager != null;
2777 switch (hitTestResult.getType()) {
2778 // `SRC_ANCHOR_TYPE` is a link.
2779 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2780 // Get the target URL.
2781 linkUrl = hitTestResult.getExtra();
2783 // Set the target URL as the title of the `ContextMenu`.
2784 menu.setHeaderTitle(linkUrl);
2786 // Add a Load URL entry.
2787 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2792 // Add a Copy URL entry.
2793 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2794 // Save the link URL in a `ClipData`.
2795 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2797 // Set the `ClipData` as the clipboard's primary clip.
2798 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2802 // Add a Download URL entry.
2803 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2804 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2805 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2806 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2808 // Store the variables for future use by `onRequestPermissionsResult()`.
2809 downloadUrl = linkUrl;
2810 downloadContentDisposition = "none";
2811 downloadContentLength = -1;
2813 // Show a dialog if the user has previously denied the permission.
2814 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2815 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2816 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2818 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2819 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2820 } else { // Show the permission request directly.
2821 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2822 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2824 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2825 // Get a handle for the download file alert dialog.
2826 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2828 // Show the download file alert dialog.
2829 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2834 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2835 menu.add(R.string.cancel);
2838 case WebView.HitTestResult.EMAIL_TYPE:
2839 // Get the target URL.
2840 linkUrl = hitTestResult.getExtra();
2842 // Set the target URL as the title of the `ContextMenu`.
2843 menu.setHeaderTitle(linkUrl);
2845 // Add a `Write Email` entry.
2846 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2847 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2848 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2850 // Parse the url and set it as the data for the `Intent`.
2851 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2853 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2854 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2857 startActivity(emailIntent);
2861 // Add a `Copy Email Address` entry.
2862 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2863 // Save the email address in a `ClipData`.
2864 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2866 // Set the `ClipData` as the clipboard's primary clip.
2867 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2871 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2872 menu.add(R.string.cancel);
2875 // `IMAGE_TYPE` is an image.
2876 case WebView.HitTestResult.IMAGE_TYPE:
2877 // Get the image URL.
2878 imageUrl = hitTestResult.getExtra();
2880 // Set the image URL as the title of the `ContextMenu`.
2881 menu.setHeaderTitle(imageUrl);
2883 // Add a `View Image` entry.
2884 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2889 // Add a `Download Image` entry.
2890 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2891 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2892 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2893 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2895 // Store the image URL for use by `onRequestPermissionResult()`.
2896 downloadImageUrl = imageUrl;
2898 // Show a dialog if the user has previously denied the permission.
2899 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2900 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2901 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2903 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2904 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2905 } else { // Show the permission request directly.
2906 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2907 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2909 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2910 // Get a handle for the download image alert dialog.
2911 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2913 // Show the download image alert dialog.
2914 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2919 // Add a `Copy URL` entry.
2920 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2921 // Save the image URL in a `ClipData`.
2922 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2924 // Set the `ClipData` as the clipboard's primary clip.
2925 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2929 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2930 menu.add(R.string.cancel);
2934 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2935 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2936 // Get the image URL.
2937 imageUrl = hitTestResult.getExtra();
2939 // Set the image URL as the title of the `ContextMenu`.
2940 menu.setHeaderTitle(imageUrl);
2942 // Add a `View Image` entry.
2943 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2948 // Add a `Download Image` entry.
2949 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2950 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2951 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2952 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2954 // Store the image URL for use by `onRequestPermissionResult()`.
2955 downloadImageUrl = imageUrl;
2957 // Show a dialog if the user has previously denied the permission.
2958 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2959 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2960 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2962 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2963 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2964 } else { // Show the permission request directly.
2965 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2966 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2968 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2969 // Get a handle for the download image alert dialog.
2970 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2972 // Show the download image alert dialog.
2973 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2978 // Add a `Copy URL` entry.
2979 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2980 // Save the image URL in a `ClipData`.
2981 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2983 // Set the `ClipData` as the clipboard's primary clip.
2984 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2988 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2989 menu.add(R.string.cancel);
2995 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2996 // Get the `EditTexts` from the `dialogFragment`.
2997 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2998 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3000 // Extract the strings from the `EditTexts`.
3001 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3002 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3004 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3005 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3006 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3007 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3009 // Display the new bookmark below the current items in the (0 indexed) list.
3010 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3012 // Create the bookmark.
3013 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3015 // Update `bookmarksCursor` with the current contents of this folder.
3016 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3018 // Update the `ListView`.
3019 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3021 // Scroll to the new bookmark.
3022 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3026 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3027 // Get handles for the views in `dialogFragment`.
3028 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3029 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3030 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3032 // Get new folder name string.
3033 String folderNameString = createFolderNameEditText.getText().toString();
3035 // Get the new folder icon `Bitmap`.
3036 Bitmap folderIconBitmap;
3037 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3038 // Get the default folder icon and convert it to a `Bitmap`.
3039 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3040 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3041 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3042 } else { // Use the `WebView` favorite icon.
3043 folderIconBitmap = favoriteIconBitmap;
3046 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3047 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3048 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3049 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3051 // Move all the bookmarks down one in the display order.
3052 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3053 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3054 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3057 // Create the folder, which will be placed at the top of the `ListView`.
3058 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3060 // Update `bookmarksCursor` with the current contents of this folder.
3061 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3063 // Update the `ListView`.
3064 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3066 // Scroll to the new folder.
3067 bookmarksListView.setSelection(0);
3071 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3072 // Get the shortcut name.
3073 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3074 String shortcutNameString = shortcutNameEditText.getText().toString();
3076 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3077 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3079 // Setup the shortcut intent.
3080 Intent shortcutIntent = new Intent();
3081 shortcutIntent.setAction(Intent.ACTION_VIEW);
3082 shortcutIntent.setData(Uri.parse(formattedUrlString));
3084 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3085 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3087 // Add the required fields to the shortcut info builder.
3088 shortcutInfoBuilder.setIcon(favoriteIcon);
3089 shortcutInfoBuilder.setIntent(shortcutIntent);
3090 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3092 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3093 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3097 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3098 switch (downloadType) {
3099 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3100 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3101 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3104 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3105 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3106 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3112 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
3113 switch (requestCode) {
3114 case DOWNLOAD_FILE_REQUEST_CODE:
3115 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3116 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3118 // On API 23, displaying the fragment must be delayed or the app will crash.
3119 if (Build.VERSION.SDK_INT == 23) {
3120 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3122 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3125 // Reset the download variables.
3127 downloadContentDisposition = "";
3128 downloadContentLength = 0;
3131 case DOWNLOAD_IMAGE_REQUEST_CODE:
3132 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3133 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3135 // On API 23, displaying the fragment must be delayed or the app will crash.
3136 if (Build.VERSION.SDK_INT == 23) {
3137 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3139 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3142 // Reset the image URL variable.
3143 downloadImageUrl = "";
3149 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3150 // Download the image if it has an HTTP or HTTPS URI.
3151 if (imageUrl.startsWith("http")) {
3152 // Get a handle for the system `DOWNLOAD_SERVICE`.
3153 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3155 // Parse `imageUrl`.
3156 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3158 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3159 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3160 if (firstPartyCookiesEnabled) {
3161 // Get the cookies for `imageUrl`.
3162 String cookies = cookieManager.getCookie(imageUrl);
3164 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3165 downloadRequest.addRequestHeader("Cookie", cookies);
3168 // Get the file name from the dialog fragment.
3169 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3170 String imageName = downloadImageNameEditText.getText().toString();
3172 // Specify the download location.
3173 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3174 // Download to the public download directory.
3175 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3176 } else { // External write permission denied.
3177 // Download to the app's external download directory.
3178 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3181 // Allow `MediaScanner` to index the download if it is a media file.
3182 downloadRequest.allowScanningByMediaScanner();
3184 // Add the URL as the description for the download.
3185 downloadRequest.setDescription(imageUrl);
3187 // Show the download notification after the download is completed.
3188 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3190 // Remove the lint warning below that `downloadManager` might be `null`.
3191 assert downloadManager != null;
3193 // Initiate the download.
3194 downloadManager.enqueue(downloadRequest);
3195 } else { // The image is not an HTTP or HTTPS URI.
3196 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3201 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3202 // Download the file if it has an HTTP or HTTPS URI.
3203 if (downloadUrl.startsWith("http")) {
3204 // Get a handle for the system `DOWNLOAD_SERVICE`.
3205 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3207 // Parse `downloadUrl`.
3208 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3210 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3211 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3212 if (firstPartyCookiesEnabled) {
3213 // Get the cookies for `downloadUrl`.
3214 String cookies = cookieManager.getCookie(downloadUrl);
3216 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3217 downloadRequest.addRequestHeader("Cookie", cookies);
3220 // Get the file name from the dialog fragment.
3221 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3222 String fileName = downloadFileNameEditText.getText().toString();
3224 // Specify the download location.
3225 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3226 // Download to the public download directory.
3227 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3228 } else { // External write permission denied.
3229 // Download to the app's external download directory.
3230 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3233 // Allow `MediaScanner` to index the download if it is a media file.
3234 downloadRequest.allowScanningByMediaScanner();
3236 // Add the URL as the description for the download.
3237 downloadRequest.setDescription(downloadUrl);
3239 // Show the download notification after the download is completed.
3240 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3242 // Remove the lint warning below that `downloadManager` might be `null`.
3243 assert downloadManager != null;
3245 // Initiate the download.
3246 downloadManager.enqueue(downloadRequest);
3247 } else { // The download is not an HTTP or HTTPS URI.
3248 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3253 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3254 // Get handles for the views from `dialogFragment`.
3255 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3256 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3257 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3259 // Store the bookmark strings.
3260 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3261 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3263 // Update the bookmark.
3264 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3265 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3266 } else { // Update the bookmark using the `WebView` favorite icon.
3267 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3268 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3269 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3270 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3272 // Update the bookmark and the favorite icon.
3273 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3276 // Update `bookmarksCursor` with the current contents of this folder.
3277 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3279 // Update the `ListView`.
3280 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3284 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3285 // Get handles for the views from `dialogFragment`.
3286 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3287 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3288 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3289 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3291 // Get the new folder name.
3292 String newFolderNameString = editFolderNameEditText.getText().toString();
3294 // Check if the favorite icon has changed.
3295 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3296 // Update the name in the database.
3297 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3298 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3299 // Get the new folder icon `Bitmap`.
3300 Bitmap folderIconBitmap;
3301 if (defaultFolderIconRadioButton.isChecked()) {
3302 // Get the default folder icon and convert it to a `Bitmap`.
3303 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3304 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3305 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3306 } else { // Use the `WebView` favorite icon.
3307 folderIconBitmap = favoriteIconBitmap;
3310 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3311 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3312 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3313 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3315 // Update the folder icon in the database.
3316 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3317 } else { // The folder icon and the name have changed.
3318 // Get the new folder icon `Bitmap`.
3319 Bitmap folderIconBitmap;
3320 if (defaultFolderIconRadioButton.isChecked()) {
3321 // Get the default folder icon and convert it to a `Bitmap`.
3322 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3323 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3324 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3325 } else { // Use the `WebView` favorite icon.
3326 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3329 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3330 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3331 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3332 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3334 // Update the folder name and icon in the database.
3335 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3338 // Update `bookmarksCursor` with the current contents of this folder.
3339 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3341 // Update the `ListView`.
3342 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3346 public void onHttpAuthenticationCancel() {
3347 // Cancel the `HttpAuthHandler`.
3348 httpAuthHandler.cancel();
3352 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3353 // Get handles for the `EditTexts`.
3354 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3355 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3357 // Proceed with the HTTP authentication.
3358 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3361 public void viewSslCertificate(View view) {
3362 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3363 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3364 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3368 public void onSslErrorCancel() {
3369 sslErrorHandler.cancel();
3373 public void onSslErrorProceed() {
3374 sslErrorHandler.proceed();
3378 public void onSslMismatchBack() {
3379 if (mainWebView.canGoBack()) { // There is a back page in the history.
3380 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3381 formattedUrlString = "";
3383 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3384 navigatingHistory = true;
3387 mainWebView.goBack();
3388 } else { // There are no pages to go back to.
3389 // Load a blank page
3395 public void onSslMismatchProceed() {
3396 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3397 ignorePinnedSslCertificate = true;
3401 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3402 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3403 formattedUrlString = "";
3405 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3406 navigatingHistory = true;
3408 // Load the history entry.
3409 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3413 public void onClearHistory() {
3414 // Clear the history.
3415 mainWebView.clearHistory();
3418 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3420 public void onBackPressed() {
3421 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3422 // Close the navigation drawer.
3423 drawerLayout.closeDrawer(GravityCompat.START);
3424 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3425 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3426 // close the bookmarks drawer.
3427 drawerLayout.closeDrawer(GravityCompat.END);
3428 } else { // A subfolder is displayed.
3429 // Place the former parent folder in `currentFolder`.
3430 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3432 // Load the new folder.
3433 loadBookmarksFolder();
3436 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3437 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3438 formattedUrlString = "";
3440 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3441 navigatingHistory = true;
3444 mainWebView.goBack();
3445 } else { // There isn't anything to do in Privacy Browser.
3446 // Pass `onBackPressed()` to the system.
3447 super.onBackPressed();
3451 // 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.
3453 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3454 // File uploads only work on API >= 21.
3455 if (Build.VERSION.SDK_INT >= 21) {
3456 // Pass the file to the WebView.
3457 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3461 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3462 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3463 String unformattedUrlString = urlTextBox.getText().toString().trim();
3465 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3466 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3467 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3468 if (!unformattedUrlString.startsWith("http")) {
3469 unformattedUrlString = "http://" + unformattedUrlString;
3472 // Initialize `unformattedUrl`.
3473 URL unformattedUrl = null;
3475 // 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.
3477 unformattedUrl = new URL(unformattedUrlString);
3478 } catch (MalformedURLException e) {
3479 e.printStackTrace();
3482 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3483 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3484 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3485 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3486 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3487 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3490 Uri.Builder formattedUri = new Uri.Builder();
3491 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3493 // Decode `formattedUri` as a `String` in `UTF-8`.
3494 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3495 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3496 // Load a blank string.
3497 formattedUrlString = "";
3498 } else { // Search for the contents of the URL box.
3499 // Sanitize the search input and convert it to a search.
3500 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3502 // Add the base search URL.
3503 formattedUrlString = searchURL + encodedUrlString;
3506 // 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.
3507 urlTextBox.clearFocus();
3510 loadUrl(formattedUrlString);
3513 private void loadUrl(String url) {// Apply any custom domain settings.
3514 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3515 formattedUrlString = url;
3517 // Apply the domain settings.
3518 applyDomainSettings(url, true, false);
3520 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3521 urlIsLoading = true;
3524 mainWebView.loadUrl(url, customHeaders);
3527 public void findPreviousOnPage(View view) {
3528 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3529 mainWebView.findNext(false);
3532 public void findNextOnPage(View view) {
3533 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3534 mainWebView.findNext(true);
3537 public void closeFindOnPage(View view) {
3538 // Delete the contents of `find_on_page_edittext`.
3539 findOnPageEditText.setText(null);
3541 // Clear the highlighted phrases.
3542 mainWebView.clearMatches();
3544 // Hide the Find on Page `RelativeLayout`.
3545 findOnPageLinearLayout.setVisibility(View.GONE);
3547 // Show the URL app bar.
3548 supportAppBar.setVisibility(View.VISIBLE);
3550 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3551 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3554 private void applyAppSettings() {
3555 // Get a handle for the shared preferences.
3556 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3558 // Store the values from the shared preferences in variables.
3559 String homepageString = sharedPreferences.getString("homepage", "https://searx.me/");
3560 String torHomepageString = sharedPreferences.getString("tor_homepage", "http://ulrn6sryqaifefld.onion/");
3561 String torSearchString = sharedPreferences.getString("tor_search", "http://ulrn6sryqaifefld.onion/?q=");
3562 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3563 String searchString = sharedPreferences.getString("search", "https://searx.me/?q=");
3564 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3565 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3566 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3567 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3568 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3569 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3570 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3571 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3573 // Set the homepage, search, and proxy options.
3574 if (proxyThroughOrbot) { // Set the Tor options.
3575 // Set `torHomepageString` as `homepage`.
3576 homepage = torHomepageString;
3578 // If formattedUrlString is null assign the homepage to it.
3579 if (formattedUrlString == null) {
3580 formattedUrlString = homepage;
3583 // Set the search URL.
3584 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3585 searchURL = torSearchCustomURLString;
3586 } else { // Use the string from the pre-built list.
3587 searchURL = torSearchString;
3590 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3591 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3593 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3595 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3597 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3600 // Display a message to the user if waiting for Orbot.
3601 if (!orbotStatus.equals("ON")) {
3602 // Set `waitingForOrbot`.
3603 waitingForOrbot = true;
3605 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3606 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3608 } else { // Set the non-Tor options.
3609 // Set `homepageString` as `homepage`.
3610 homepage = homepageString;
3612 // If formattedUrlString is null assign the homepage to it.
3613 if (formattedUrlString == null) {
3614 formattedUrlString = homepage;
3617 // Set the search URL.
3618 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3619 searchURL = searchCustomURLString;
3620 } else { // Use the string from the pre-built list.
3621 searchURL = searchString;
3624 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3625 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3627 // Set the default `appBar` background. `this` refers to the context.
3629 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3631 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3634 // Reset `waitingForOrbot.
3635 waitingForOrbot = false;
3638 // Set Do Not Track status.
3639 if (doNotTrackEnabled) {
3640 customHeaders.put("DNT", "1");
3642 customHeaders.remove("DNT");
3645 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3646 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3647 if (hideSystemBarsOnFullscreen) { // Hide everything.
3648 // Remove the translucent navigation setting if it is currently flagged.
3649 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3651 // Remove the translucent status bar overlay.
3652 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3654 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3655 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3657 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3658 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3659 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3661 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3662 } else { // Hide everything except the status and navigation bars.
3663 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3664 rootCoordinatorLayout.setSystemUiVisibility(0);
3666 // Add the translucent status flag if it is unset.
3667 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3669 if (translucentNavigationBarOnFullscreen) {
3670 // Set the navigation bar to be translucent.
3671 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3673 // Set the navigation bar to be black.
3674 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3677 } else { // Privacy Browser is not in full screen browsing mode.
3678 // Reset the full screen tracker, which could be true if Privacy Browser was in full screen mode before entering settings and full screen browsing was disabled.
3679 inFullScreenBrowsingMode = false;
3681 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3682 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3686 // Show the `BannerAd` in the free flavor.
3687 if (BuildConfig.FLAVOR.contentEquals("free")) {
3688 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3689 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3692 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3693 rootCoordinatorLayout.setSystemUiVisibility(0);
3695 // Remove the translucent navigation bar flag if it is set.
3696 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3698 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3699 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3701 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3702 rootCoordinatorLayout.setFitsSystemWindows(true);
3706 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3707 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3708 @SuppressWarnings("deprecation")
3709 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3710 // Parse the URL into a URI.
3711 Uri uri = Uri.parse(url);
3713 // Extract the domain from `uri`.
3714 String hostName = uri.getHost();
3716 // Initialize `loadingNewDomainName`.
3717 boolean loadingNewDomainName;
3719 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3720 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3721 //noinspection SimplifiableIfStatement
3722 if ((hostName == null) || (currentDomainName == null)) {
3723 loadingNewDomainName = true;
3724 } else { // Determine if `hostName` equals `currentDomainName`.
3725 loadingNewDomainName = !hostName.equals(currentDomainName);
3728 // Strings don't like to be null.
3729 if (hostName == null) {
3733 // 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.
3734 if (loadingNewDomainName) {
3735 // Set the new `hostname` as the `currentDomainName`.
3736 currentDomainName = hostName;
3738 // Reset `ignorePinnedSslCertificate`.
3739 ignorePinnedSslCertificate = false;
3741 // Reset the favorite icon if specified.
3742 if (resetFavoriteIcon) {
3743 favoriteIconBitmap = favoriteIconDefaultBitmap;
3744 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3747 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3748 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3749 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3751 // Get a full cursor from `domainsDatabaseHelper`.
3752 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3754 // Initialize `domainSettingsSet`.
3755 Set<String> domainSettingsSet = new HashSet<>();
3757 // Get the domain name column index.
3758 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3760 // Populate `domainSettingsSet`.
3761 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3762 // Move `domainsCursor` to the current row.
3763 domainNameCursor.moveToPosition(i);
3765 // Store the domain name in `domainSettingsSet`.
3766 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3769 // Close `domainNameCursor.
3770 domainNameCursor.close();
3772 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3773 domainSettingsApplied = false;
3774 String domainNameInDatabase = null;
3776 // Check the hostname.
3777 if (domainSettingsSet.contains(hostName)) {
3778 domainSettingsApplied = true;
3779 domainNameInDatabase = hostName;
3782 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3783 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3784 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3785 // Apply the domain settings.
3786 domainSettingsApplied = true;
3788 // Store the applied domain names as it appears in the database.
3789 domainNameInDatabase = "*." + hostName;
3792 // Strip out the lowest subdomain of of the host name.
3793 hostName = hostName.substring(hostName.indexOf(".") + 1);
3797 // Get a handle for the shared preference.
3798 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3800 // Store the general preference information.
3801 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3802 String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3803 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3804 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3805 nightMode = sharedPreferences.getBoolean("night_mode", false);
3807 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3808 // Get a cursor for the current host and move it to the first position.
3809 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3810 currentHostDomainSettingsCursor.moveToFirst();
3812 // Get the settings from the cursor.
3813 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3814 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3815 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3816 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3817 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3818 // Form data can be removed once the minimum API >= 26.
3819 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3820 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3821 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3822 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3823 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3824 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3825 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3826 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3827 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3828 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3829 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3830 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3831 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3832 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3833 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3834 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3835 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3836 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3837 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3839 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3840 switch (nightModeInt) {
3841 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3845 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3850 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3852 javaScriptEnabled = true;
3855 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3856 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3857 pinnedDomainSslStartDate = null;
3859 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3862 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3863 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3864 pinnedDomainSslEndDate = null;
3866 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3869 // Close `currentHostDomainSettingsCursor`.
3870 currentHostDomainSettingsCursor.close();
3872 // Apply the domain settings.
3873 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3874 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3875 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3877 // Apply the form data setting if the API < 26.
3878 if (Build.VERSION.SDK_INT < 26) {
3879 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3882 // Apply the font size.
3883 if (fontSize == 0) { // Apply the default font size.
3884 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3885 } else { // Apply the specified font size.
3886 mainWebView.getSettings().setTextZoom(fontSize);
3889 // Set third-party cookies status if API >= 21.
3890 if (Build.VERSION.SDK_INT >= 21) {
3891 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3894 // 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.
3895 // <https://redmine.stoutner.com/issues/160>
3896 if (!urlIsLoading) {
3897 // Set the user agent.
3898 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3899 // Get the array position of the default user agent name.
3900 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3902 // Set the user agent according to the system default.
3903 switch (defaultUserAgentArrayPosition) {
3904 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3905 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3906 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3909 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3910 // Set the user agent to `""`, which uses the default value.
3911 mainWebView.getSettings().setUserAgentString("");
3914 case SETTINGS_CUSTOM_USER_AGENT:
3915 // Set the custom user agent.
3916 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3920 // Get the user agent string from the user agent data array
3921 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3923 } else { // Set the user agent according to the stored name.
3924 // Get the array position of the user agent name.
3925 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3927 switch (userAgentArrayPosition) {
3928 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3929 mainWebView.getSettings().setUserAgentString(userAgentName);
3932 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3933 // Set the user agent to `""`, which uses the default value.
3934 mainWebView.getSettings().setUserAgentString("");
3938 // Get the user agent string from the user agent data array.
3939 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3943 // Set swipe to refresh.
3944 switch (swipeToRefreshInt) {
3945 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3946 // Set swipe to refresh according to the default.
3947 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3950 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3951 // Enable swipe to refresh.
3952 swipeRefreshLayout.setEnabled(true);
3955 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3956 // Disable swipe to refresh.
3957 swipeRefreshLayout.setEnabled(false);
3960 // Store the applied user agent string, which is used in the View Source activity.
3961 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3964 // 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.
3966 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3968 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3970 } else { // The new URL does not have custom domain settings. Load the defaults.
3971 // Store the values from `sharedPreferences` in variables.
3972 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3973 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3974 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3975 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3976 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false); // Form data can be removed once the minimum API >= 26.
3977 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3978 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3979 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3980 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3981 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
3982 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
3984 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3986 javaScriptEnabled = true;
3989 // Apply the default settings.
3990 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3991 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3992 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3993 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3994 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3996 // Apply the form data setting if the API < 26.
3997 if (Build.VERSION.SDK_INT < 26) {
3998 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4001 // Reset the pinned SSL certificate information.
4002 domainSettingsDatabaseId = -1;
4003 pinnedDomainSslCertificate = false;
4004 pinnedDomainSslIssuedToCNameString = "";
4005 pinnedDomainSslIssuedToONameString = "";
4006 pinnedDomainSslIssuedToUNameString = "";
4007 pinnedDomainSslIssuedByCNameString = "";
4008 pinnedDomainSslIssuedByONameString = "";
4009 pinnedDomainSslIssuedByUNameString = "";
4010 pinnedDomainSslStartDate = null;
4011 pinnedDomainSslEndDate = null;
4013 // Set third-party cookies status if API >= 21.
4014 if (Build.VERSION.SDK_INT >= 21) {
4015 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4018 // 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.
4019 // <https://redmine.stoutner.com/issues/160>
4020 if (!urlIsLoading) {
4021 // Get the array position of the user agent name.
4022 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4024 // Set the user agent.
4025 switch (userAgentArrayPosition) {
4026 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4027 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4028 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4031 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4032 // Set the user agent to `""`, which uses the default value.
4033 mainWebView.getSettings().setUserAgentString("");
4036 case SETTINGS_CUSTOM_USER_AGENT:
4037 // Set the custom user agent.
4038 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4042 // Get the user agent string from the user agent data array
4043 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4046 // Store the applied user agent string, which is used in the View Source activity.
4047 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4050 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4051 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4054 // Close `domainsDatabaseHelper`.
4055 domainsDatabaseHelper.close();
4057 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
4058 onTheFlyDisplayImagesSet = false;
4059 setDisplayWebpageImages();
4061 // Update the privacy icons, but only if `mainMenu` has already been populated.
4062 if (mainMenu != null) {
4063 updatePrivacyIcons(true);
4067 // Reload the website if returning from the Domains activity.
4068 if (reloadWebsite) {
4069 mainWebView.reload();
4073 private void setDisplayWebpageImages() {
4074 if (!onTheFlyDisplayImagesSet) {
4075 if (domainSettingsApplied) { // Custom domain settings are applied.
4076 switch (displayWebpageImagesInt) {
4077 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4078 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4081 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4082 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4085 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4086 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4089 } else { // Default settings are applied.
4090 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4095 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4096 // Get handles for the menu items.
4097 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4098 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4099 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4100 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4102 // Update the privacy icon.
4103 if (javaScriptEnabled) { // JavaScript is enabled.
4104 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4105 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4106 privacyMenuItem.setIcon(R.drawable.warning);
4107 } else { // All the dangerous features are disabled.
4108 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4111 // Update the first-party cookies icon.
4112 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4113 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4114 } else { // First-party cookies are disabled.
4116 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4118 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4122 // Update the DOM storage icon.
4123 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4124 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4125 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4127 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4129 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4131 } else { // JavaScript is disabled, so DOM storage is ghosted.
4133 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4135 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4139 // Update the refresh icon.
4141 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4143 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4146 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4147 if (runInvalidateOptionsMenu) {
4148 invalidateOptionsMenu();
4152 private void highlightUrlText() {
4153 String urlString = urlTextBox.getText().toString();
4155 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4156 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4157 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4158 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4161 // Get the index of the `/` immediately after the domain name.
4162 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4164 // De-emphasize the text after the domain name.
4165 if (endOfDomainName > 0) {
4166 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4170 private void loadBookmarksFolder() {
4171 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4172 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4174 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4175 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4177 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4178 // Inflate the individual item layout. `false` does not attach it to the root.
4179 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4183 public void bindView(View view, Context context, Cursor cursor) {
4184 // Get handles for the views.
4185 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4186 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4188 // Get the favorite icon byte array from the cursor.
4189 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4191 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4192 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4194 // Display the bitmap in `bookmarkFavoriteIcon`.
4195 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4197 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4198 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4199 bookmarkNameTextView.setText(bookmarkNameString);
4201 // Make the font bold for folders.
4202 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4203 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4204 } else { // Reset the font to default for normal bookmarks.
4205 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4210 // Populate the `ListView` with the adapter.
4211 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4213 // Set the bookmarks drawer title.
4214 if (currentBookmarksFolder.isEmpty()) {
4215 bookmarksTitleTextView.setText(R.string.bookmarks);
4217 bookmarksTitleTextView.setText(currentBookmarksFolder);