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 // `refreshMenuItem` is used in `onCreate()` and `onCreateOptionsItem()`.
415 private MenuItem refreshMenuItem;
417 // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
418 private boolean displayAdditionalAppBarIcons;
420 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
421 private ActionBarDrawerToggle drawerToggle;
423 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
424 private Toolbar supportAppBar;
426 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
427 private EditText urlTextBox;
429 // The color spans are used in `onCreate()` and `highlightUrlText()`.
430 private ForegroundColorSpan redColorSpan;
431 private ForegroundColorSpan initialGrayColorSpan;
432 private ForegroundColorSpan finalGrayColorSpan;
434 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
435 private SslErrorHandler sslErrorHandler;
437 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
438 private static HttpAuthHandler httpAuthHandler;
440 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
441 private InputMethodManager inputMethodManager;
443 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
444 private RelativeLayout mainWebViewRelativeLayout;
446 // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
447 private boolean urlIsLoading;
449 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
450 private boolean pinnedDomainSslCertificate;
452 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
453 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
455 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
456 private ListView bookmarksListView;
458 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
459 private TextView bookmarksTitleTextView;
461 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
462 private Cursor bookmarksCursor;
464 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
465 private CursorAdapter bookmarksCursorAdapter;
467 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
468 private String oldFolderNameString;
470 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
471 private ValueCallback<Uri[]> fileChooserCallback;
473 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
474 private String downloadUrl;
475 private String downloadContentDisposition;
476 private long downloadContentLength;
478 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
479 private String downloadImageUrl;
481 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
482 private ArrayAdapter<CharSequence> userAgentNamesArray;
483 private String[] userAgentDataArray;
485 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
486 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
487 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
490 // 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.
491 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
492 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
493 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
494 @SuppressWarnings("deprecation")
495 protected void onCreate(Bundle savedInstanceState) {
496 // Get a handle for the shared preferences.
497 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
499 // Get the theme and screenshot preferences.
500 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
501 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
503 // Disable screenshots if not allowed.
504 if (!allowScreenshots) {
505 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
508 // Set the activity theme.
510 setTheme(R.style.PrivacyBrowserDark);
512 setTheme(R.style.PrivacyBrowserLight);
515 // Run the default commands.
516 super.onCreate(savedInstanceState);
518 // Set the content view.
519 setContentView(R.layout.main_drawerlayout);
521 // Get a handle for `inputMethodManager`.
522 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
524 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
525 supportAppBar = findViewById(R.id.app_bar);
526 setSupportActionBar(supportAppBar);
527 appBar = getSupportActionBar();
529 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
530 assert appBar != null;
532 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
533 appBar.setCustomView(R.layout.url_app_bar);
534 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
536 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
537 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
538 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
539 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
541 // Get a handle for `urlTextBox`.
542 urlTextBox = findViewById(R.id.url_edittext);
544 // Remove the formatting from `urlTextBar` when the user is editing the text.
545 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
546 if (hasFocus) { // The user is editing `urlTextBox`.
547 // Remove the highlighting.
548 urlTextBox.getText().removeSpan(redColorSpan);
549 urlTextBox.getText().removeSpan(initialGrayColorSpan);
550 urlTextBox.getText().removeSpan(finalGrayColorSpan);
551 } else { // The user has stopped editing `urlTextBox`.
552 // Reapply the highlighting.
557 // Set the go button on the keyboard to load the URL in `urlTextBox`.
558 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
559 // If the event is a key-down event on the `enter` button, load the URL.
560 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
561 // Load the URL into the mainWebView and consume the event.
563 loadUrlFromTextBox();
564 } catch (UnsupportedEncodingException e) {
567 // If the enter key was pressed, consume the event.
570 // If any other key was pressed, do not consume the event.
575 // Set `waitingForOrbotHTMLString`.
576 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
578 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
579 currentDomainName = "";
580 orbotStatus = "unknown";
581 waitingForOrbot = false;
583 // Create an Orbot status `BroadcastReceiver`.
584 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
586 public void onReceive(Context context, Intent intent) {
587 // Store the content of the status message in `orbotStatus`.
588 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
590 // If we are waiting on Orbot, load the website now that Orbot is connected.
591 if (orbotStatus.equals("ON") && waitingForOrbot) {
592 // Reset `waitingForOrbot`.
593 waitingForOrbot = false;
595 // Load `formattedUrlString
596 loadUrl(formattedUrlString);
601 // Register `orbotStatusBroadcastReceiver` on `this` context.
602 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
604 // Get handles for views that need to be accessed.
605 drawerLayout = findViewById(R.id.drawerlayout);
606 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
607 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
608 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
609 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
610 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
611 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
612 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
613 mainWebView = findViewById(R.id.main_webview);
614 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
615 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
616 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
617 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
618 favoriteIconImageView = findViewById(R.id.favorite_icon);
620 // 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.
622 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
623 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
624 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
625 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
627 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
628 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
629 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
630 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
633 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
634 launchBookmarksActivityFab.setOnClickListener(v -> {
635 // Create an intent to launch the bookmarks activity.
636 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
638 // Include the current folder with the `Intent`.
639 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
642 startActivity(bookmarksIntent);
645 // Set the create new bookmark folder FAB to display an alert dialog.
646 createBookmarkFolderFab.setOnClickListener(v -> {
647 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
648 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
649 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
652 // Set the create new bookmark FAB to display an alert dialog.
653 createBookmarkFab.setOnClickListener(view -> {
654 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
655 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
656 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
659 // Create a double-tap listener to toggle full-screen mode.
660 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
661 // Override `onDoubleTap()`. All other events are handled using the default settings.
663 public boolean onDoubleTap(MotionEvent event) {
664 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
665 // Toggle `inFullScreenBrowsingMode`.
666 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
668 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
669 // Hide the `appBar`.
672 // Hide the banner ad in the free flavor.
673 if (BuildConfig.FLAVOR.contentEquals("free")) {
674 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
675 AdHelper.hideAd(findViewById(R.id.adview));
678 // Modify the system bars.
679 if (hideSystemBarsOnFullscreen) { // Hide everything.
680 // Remove the translucent overlays.
681 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
683 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
684 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
686 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
687 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
688 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
690 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
692 // Set `rootCoordinatorLayout` to fill the whole screen.
693 rootCoordinatorLayout.setFitsSystemWindows(false);
694 } else { // Hide everything except the status and navigation bars.
695 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
696 rootCoordinatorLayout.setFitsSystemWindows(false);
698 // 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.
699 if (translucentNavigationBarOnFullscreen) {
700 // Set the navigation bar to be translucent.
701 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
704 } else { // Switch to normal viewing mode.
705 // Show the `appBar`.
708 // Show the `BannerAd` in the free flavor.
709 if (BuildConfig.FLAVOR.contentEquals("free")) {
710 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
711 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
714 // Remove the translucent navigation bar flag if it is set.
715 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
717 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
718 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
720 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
721 rootCoordinatorLayout.setSystemUiVisibility(0);
723 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
724 rootCoordinatorLayout.setFitsSystemWindows(true);
727 // Consume the double-tap.
729 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
735 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
736 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
737 // Call `performClick()` on the view, which is required for accessibility.
740 // Send the `event` to `gestureDetector`.
741 return gestureDetector.onTouchEvent(event);
744 // Update `findOnPageCountTextView`.
745 mainWebView.setFindListener(new WebView.FindListener() {
746 // Get a handle for `findOnPageCountTextView`.
747 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
750 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
751 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
752 // Set `findOnPageCountTextView` to `0/0`.
753 findOnPageCountTextView.setText(R.string.zero_of_zero);
754 } else if (isDoneCounting) { // There are matches.
755 // `activeMatchOrdinal` is zero-based.
756 int activeMatch = activeMatchOrdinal + 1;
758 // Build the match string.
759 String matchString = activeMatch + "/" + numberOfMatches;
761 // Set `findOnPageCountTextView`.
762 findOnPageCountTextView.setText(matchString);
767 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
768 findOnPageEditText.addTextChangedListener(new TextWatcher() {
770 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
775 public void onTextChanged(CharSequence s, int start, int before, int count) {
780 public void afterTextChanged(Editable s) {
781 // Search for the text in `mainWebView`.
782 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
786 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
787 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
788 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
789 // Hide the soft keyboard. `0` indicates no additional flags.
790 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
792 // Consume the event.
794 } else { // A different key was pressed.
795 // Do not consume the event.
800 // Implement swipe to refresh
801 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
802 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
803 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
805 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
806 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
807 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
809 // Listen for touches on the navigation menu.
810 final NavigationView navigationView = findViewById(R.id.navigationview);
811 navigationView.setNavigationItemSelectedListener(this);
813 // 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.
814 final Menu navigationMenu = navigationView.getMenu();
815 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
816 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
817 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
818 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
820 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
821 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
822 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
824 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
825 currentBookmarksFolder = "";
827 // Load the home folder, which is `""` in the database.
828 loadBookmarksFolder();
830 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
831 // Convert the id from long to int to match the format of the bookmarks database.
832 int databaseID = (int) id;
834 // Get the bookmark cursor for this ID and move it to the first row.
835 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
836 bookmarkCursor.moveToFirst();
838 // Act upon the bookmark according to the type.
839 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
840 // Store the new folder name in `currentBookmarksFolder`.
841 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
843 // Load the new folder.
844 loadBookmarksFolder();
845 } else { // The selected bookmark is not a folder.
846 // Load the bookmark URL.
847 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
849 // Close the bookmarks drawer.
850 drawerLayout.closeDrawer(GravityCompat.END);
853 // Close the `Cursor`.
854 bookmarkCursor.close();
857 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
858 // Convert the database ID from `long` to `int`.
859 int databaseId = (int) id;
861 // Find out if the selected bookmark is a folder.
862 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
865 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
866 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
868 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
869 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
870 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
872 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
873 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
874 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
877 // Consume the event.
881 // The `DrawerListener` is used to update the Navigation Menu.
882 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
884 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
888 public void onDrawerOpened(@NonNull View drawerView) {
892 public void onDrawerClosed(@NonNull View drawerView) {
896 public void onDrawerStateChanged(int newState) {
897 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
898 // Calculate the total blocked requests counter.
899 int totalBlockedRequests = easyListBlockedRequests + easyPrivacyBlockedRequests + fanboysAnnoyanceListBlockedRequests + fanboysSocialBlockingListBlockedRequests +
900 ultraPrivacyBlockedRequests + thirdPartyBlockedRequests;
902 // Update the back, forward, history, and requests menu items.
903 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
904 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
905 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
906 navigationRequestsMenuItem.setTitle(getResources().getString(R.string.requests) + " - " + totalBlockedRequests);
908 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
909 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
911 // Clear the focus from `urlTextBox` if it has it.
912 urlTextBox.clearFocus();
917 // drawerToggle creates the hamburger icon at the start of the AppBar.
918 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
920 // Get a handle for the progress bar.
921 final ProgressBar progressBar = findViewById(R.id.progress_bar);
923 mainWebView.setWebChromeClient(new WebChromeClient() {
924 // Update the progress bar when a page is loading.
926 public void onProgressChanged(WebView view, int progress) {
927 // Inject the night mode CSS if night mode is enabled.
929 // `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
930 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
931 // `border: none` removes all borders, which can also be used to underline text.
932 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
933 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
934 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
935 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
936 // Initialize a `Handler` to display `mainWebView`.
937 Handler displayWebViewHandler = new Handler();
939 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
940 Runnable displayWebViewRunnable = () -> {
941 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
942 if (progressBar.getVisibility() == View.GONE) {
943 mainWebView.setVisibility(View.VISIBLE);
947 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
948 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
952 // Update the progress bar.
953 progressBar.setProgress(progress);
955 // Set the visibility of the progress bar.
956 if (progress < 100) {
957 // Show the progress bar.
958 progressBar.setVisibility(View.VISIBLE);
960 // Hide the progress bar.
961 progressBar.setVisibility(View.GONE);
963 // Display `mainWebView` if night mode is disabled.
964 // 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
965 // currently enabled.
967 mainWebView.setVisibility(View.VISIBLE);
970 //Stop the swipe to refresh indicator if it is running
971 swipeRefreshLayout.setRefreshing(false);
975 // Set the favorite icon when it changes.
977 public void onReceivedIcon(WebView view, Bitmap icon) {
978 // Only update the favorite icon if the website has finished loading.
979 if (progressBar.getVisibility() == View.GONE) {
980 // Save a copy of the favorite icon.
981 favoriteIconBitmap = icon;
983 // Place the favorite icon in the appBar.
984 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
988 // Save a copy of the title when it changes.
990 public void onReceivedTitle(WebView view, String title) {
991 // Save a copy of the title.
992 webViewTitle = title;
995 // Enter full screen video.
997 public void onShowCustomView(View view, CustomViewCallback callback) {
998 // Set the full screen video flag.
999 displayingFullScreenVideo = true;
1001 // Pause the ad if this is the free flavor.
1002 if (BuildConfig.FLAVOR.contentEquals("free")) {
1003 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1004 AdHelper.pauseAd(findViewById(R.id.adview));
1007 // Remove the translucent overlays.
1008 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1010 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1011 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1013 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1014 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1015 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1017 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1019 // Set `rootCoordinatorLayout` to fill the entire screen.
1020 rootCoordinatorLayout.setFitsSystemWindows(false);
1022 // Disable the sliding drawers.
1023 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1025 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1026 fullScreenVideoFrameLayout.addView(view);
1027 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1030 // Exit full screen video.
1032 public void onHideCustomView() {
1033 // Unset the full screen video flag.
1034 displayingFullScreenVideo = true;
1036 // Hide `fullScreenVideoFrameLayout`.
1037 fullScreenVideoFrameLayout.removeAllViews();
1038 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1040 // Enable the sliding drawers.
1041 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1043 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1044 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1045 if (hideSystemBarsOnFullscreen) { // Hide everything.
1046 // Remove the translucent navigation setting if it is currently flagged.
1047 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1049 // Remove the translucent status bar overlay.
1050 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1052 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1053 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1055 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1056 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1057 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1059 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1060 } else { // Hide everything except the status and navigation bars.
1061 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1062 rootCoordinatorLayout.setSystemUiVisibility(0);
1064 // Add the translucent status flag if it is unset.
1065 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1067 if (translucentNavigationBarOnFullscreen) {
1068 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1069 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1071 // Set the navigation bar to be black.
1072 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1075 } else { // Switch to normal viewing mode.
1076 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1077 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1081 // Show the `BannerAd` in the free flavor.
1082 if (BuildConfig.FLAVOR.contentEquals("free")) {
1083 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1084 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1087 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1088 rootCoordinatorLayout.setSystemUiVisibility(0);
1090 // Remove the translucent navigation bar flag if it is set.
1091 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1093 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1094 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1096 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1097 rootCoordinatorLayout.setFitsSystemWindows(true);
1100 // Show the ad if this is the free flavor.
1101 if (BuildConfig.FLAVOR.contentEquals("free")) {
1102 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1103 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1109 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1110 // Show the file chooser if the device is running API >= 21.
1111 if (Build.VERSION.SDK_INT >= 21) {
1112 // Store the file path callback.
1113 fileChooserCallback = filePathCallback;
1115 // Create an intent to open a chooser based ont the file chooser parameters.
1116 Intent fileChooserIntent = fileChooserParams.createIntent();
1118 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1119 startActivityForResult(fileChooserIntent, 0);
1125 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1126 registerForContextMenu(mainWebView);
1128 // Allow the downloading of files.
1129 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1130 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1131 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1132 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1134 // Store the variables for future use by `onRequestPermissionsResult()`.
1136 downloadContentDisposition = contentDisposition;
1137 downloadContentLength = contentLength;
1139 // Show a dialog if the user has previously denied the permission.
1140 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1141 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1142 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1144 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1145 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1146 } else { // Show the permission request directly.
1147 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1148 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1150 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1151 // Get a handle for the download file alert dialog.
1152 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1154 // Show the download file alert dialog.
1155 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1159 // Allow pinch to zoom.
1160 mainWebView.getSettings().setBuiltInZoomControls(true);
1162 // Hide zoom controls.
1163 mainWebView.getSettings().setDisplayZoomControls(false);
1165 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1166 mainWebView.getSettings().setUseWideViewPort(true);
1168 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1169 mainWebView.getSettings().setLoadWithOverviewMode(true);
1171 // Explicitly disable geolocation.
1172 mainWebView.getSettings().setGeolocationEnabled(false);
1174 // Initialize cookieManager.
1175 cookieManager = CookieManager.getInstance();
1177 // 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).
1178 customHeaders.put("X-Requested-With", "");
1180 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1181 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1183 // Get the intent that started the app.
1184 final Intent launchingIntent = getIntent();
1186 // Extract the launching intent data as `launchingIntentUriData`.
1187 final Uri launchingIntentUriData = launchingIntent.getData();
1189 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1190 if (launchingIntentUriData != null) {
1191 formattedUrlString = launchingIntentUriData.toString();
1194 // Get a handle for the `Runtime`.
1195 privacyBrowserRuntime = Runtime.getRuntime();
1197 // Store the application's private data directory.
1198 privateDataDirectoryString = getApplicationInfo().dataDir;
1199 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1201 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1202 inFullScreenBrowsingMode = false;
1204 // Initialize the privacy settings variables.
1205 javaScriptEnabled = false;
1206 firstPartyCookiesEnabled = false;
1207 thirdPartyCookiesEnabled = false;
1208 domStorageEnabled = false;
1209 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1212 // Initialize the WebView title.
1213 webViewTitle = getString(R.string.no_title);
1215 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1216 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1217 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1218 assert favoriteIconBitmapDrawable != null;
1219 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1221 // If the favorite icon is null, load the default.
1222 if (favoriteIconBitmap == null) {
1223 favoriteIconBitmap = favoriteIconDefaultBitmap;
1226 // Initialize the user agent array adapter and string array.
1227 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1228 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1230 // Apply the app settings from the shared preferences.
1233 // Instantiate the block list helper.
1234 BlockListHelper blockListHelper = new BlockListHelper();
1236 // Initialize the list of resource requests.
1237 resourceRequests = new ArrayList<>();
1239 // Parse the block lists.
1240 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1241 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1242 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1243 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1244 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1246 // Store the list versions.
1247 easyListVersion = easyList.get(0).get(0)[0];
1248 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1249 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1250 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1251 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1253 mainWebView.setWebViewClient(new WebViewClient() {
1254 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1255 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1256 @SuppressWarnings("deprecation")
1258 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1259 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1260 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1261 formattedUrlString = "";
1263 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1264 applyDomainSettings(url, true, false);
1266 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1268 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1269 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1270 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1272 // Parse the url and set it as the data for the intent.
1273 emailIntent.setData(Uri.parse(url));
1275 // Open the email program in a new task instead of as part of Privacy Browser.
1276 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1279 startActivity(emailIntent);
1281 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1283 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1284 // Open the dialer and load the phone number, but wait for the user to place the call.
1285 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1287 // Add the phone number to the intent.
1288 dialIntent.setData(Uri.parse(url));
1290 // Open the dialer in a new task instead of as part of Privacy Browser.
1291 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1294 startActivity(dialIntent);
1296 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1298 } else { // Load a system chooser to select an app that can handle the URL.
1299 // Open an app that can handle the URL.
1300 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1302 // Add the URL to the intent.
1303 genericIntent.setData(Uri.parse(url));
1305 // List all apps that can handle the URL instead of just opening the first one.
1306 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1308 // Open the app in a new task instead of as part of Privacy Browser.
1309 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1311 // Start the app or display a snackbar if no app is available to handle the URL.
1313 startActivity(genericIntent);
1314 } catch (ActivityNotFoundException exception) {
1315 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1318 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1323 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1324 @SuppressWarnings("deprecation")
1326 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1327 // Create an empty web resource response to be used if the resource request is blocked.
1328 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1330 // Reset the whitelist results tracker.
1331 whiteListResultStringArray = null;
1333 // Initialize the third party request tracker.
1334 boolean isThirdPartyRequest = false;
1336 // Initialize the current domain string.
1337 String currentDomain = "";
1339 // Nobody is happy when comparing null strings.
1340 if (!(formattedUrlString == null) && !(url == null)) {
1341 // Get the domain strings to URIs.
1342 Uri currentDomainUri = Uri.parse(formattedUrlString);
1343 Uri requestDomainUri = Uri.parse(url);
1345 // Get the domain host names.
1346 String currentBaseDomain = currentDomainUri.getHost();
1347 String requestBaseDomain = requestDomainUri.getHost();
1349 // Update the current domain variable.
1350 currentDomain = currentBaseDomain;
1352 // Only compare the current base domain and the request base domain if neither is null.
1353 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1354 // Determine the current base domain.
1355 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1356 // Remove the first subdomain.
1357 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1360 // Determine the request base domain.
1361 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1362 // Remove the first subdomain.
1363 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1366 // Update the third party request tracker.
1367 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1371 // Block third-party requests if enabled.
1372 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1373 // Increment the third-party blocked requests counter.
1374 thirdPartyBlockedRequests++;
1376 // Add the request to the log.
1377 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1379 // Return an empty web resource response.
1380 return emptyWebResourceResponse;
1383 // Check UltraPrivacy if it is enabled.
1384 if (ultraPrivacyEnabled) {
1385 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1386 // Increment the UltraPrivacy blocked requests counter.
1387 ultraPrivacyBlockedRequests++;
1389 // The resource request was blocked. Return an empty web resource response.
1390 return emptyWebResourceResponse;
1393 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1394 if (whiteListResultStringArray != null) {
1395 // Add a whitelist entry to the resource requests array.
1396 resourceRequests.add(whiteListResultStringArray);
1398 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1403 // Check EasyList if it is enabled.
1404 if (easyListEnabled) {
1405 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1406 // Increment the EasyList blocked requests counter.
1407 easyListBlockedRequests++;
1409 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1410 whiteListResultStringArray = null;
1412 // The resource request was blocked. Return an empty web resource response.
1413 return emptyWebResourceResponse;
1417 // Check EasyPrivacy if it is enabled.
1418 if (easyPrivacyEnabled) {
1419 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1420 // Increment the EasyPrivacy blocked requests counter.
1421 easyPrivacyBlockedRequests++;
1423 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1424 whiteListResultStringArray = null;
1426 // The resource request was blocked. Return an empty web resource response.
1427 return emptyWebResourceResponse;
1431 // Check Fanboy’s Annoyance List if it is enabled.
1432 if (fanboysAnnoyanceListEnabled) {
1433 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1434 // Increment the Fanboy's Annoyance List blocked requests counter.
1435 fanboysAnnoyanceListBlockedRequests++;
1437 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1438 whiteListResultStringArray = null;
1440 // The resource request was blocked. Return an empty web resource response.
1441 return emptyWebResourceResponse;
1443 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1444 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1445 // Increment the Fanboy's Social Blocking List blocked requests counter.
1446 fanboysSocialBlockingListBlockedRequests++;
1448 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1449 whiteListResultStringArray = null;
1451 // The resource request was blocked. Return an empty web resource response.
1452 return emptyWebResourceResponse;
1456 // Add the request to the log because it hasn't been processed by any of the previous checks.
1457 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1458 resourceRequests.add(whiteListResultStringArray);
1459 } else { // The request didn't match any blocklist entry. Log it as a defult request.
1460 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1463 // The resource request has not been blocked. `return null` loads the requested resource.
1467 // Handle HTTP authentication requests.
1469 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1470 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1471 httpAuthHandler = handler;
1473 // Display the HTTP authentication dialog.
1474 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1475 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1478 // Update the URL in urlTextBox when the page starts to load.
1480 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1481 // Reset the list of resource requests.
1482 resourceRequests.clear();
1484 // Initialize the counters for requests blocked by each blocklist.
1485 easyListBlockedRequests = 0;
1486 easyPrivacyBlockedRequests = 0;
1487 fanboysAnnoyanceListBlockedRequests = 0;
1488 fanboysSocialBlockingListBlockedRequests = 0;
1489 ultraPrivacyBlockedRequests = 0;
1490 thirdPartyBlockedRequests = 0;
1492 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1494 mainWebView.setVisibility(View.INVISIBLE);
1497 // Hide the keyboard. `0` indicates no additional flags.
1498 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1500 // Check to see if Privacy Browser is waiting on Orbot.
1501 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1502 // 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.
1503 formattedUrlString = url;
1505 // Display the formatted URL text.
1506 urlTextBox.setText(formattedUrlString);
1508 // Apply text highlighting to `urlTextBox`.
1511 // Apply any custom domain settings if the URL was loaded by navigating history.
1512 if (navigatingHistory) {
1513 // Reset `navigatingHistory`.
1514 navigatingHistory = false;
1516 // Apply the domain settings.
1517 applyDomainSettings(url, true, false);
1520 // 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.
1521 urlIsLoading = true;
1523 // Replace Refresh with Stop if the menu item has been created. (The WebView typically begins loading before the menu items are instantiated.)
1524 if (refreshMenuItem != null) {
1526 refreshMenuItem.setTitle(R.string.stop);
1528 // If the icon is displayed in the AppBar, set it according to the theme.
1529 if (displayAdditionalAppBarIcons) {
1531 refreshMenuItem.setIcon(R.drawable.close_dark);
1533 refreshMenuItem.setIcon(R.drawable.close_light);
1540 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1542 public void onPageFinished(WebView view, String url) {
1543 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1544 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1545 cookieManager.flush();
1548 // Update the Refresh menu item if it has been created.
1549 if (refreshMenuItem != null) {
1550 // Reset the Refresh title.
1551 refreshMenuItem.setTitle(R.string.refresh);
1553 // If the icon is displayed in the AppBar, reset it according to the theme.
1554 if (displayAdditionalAppBarIcons) {
1556 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1558 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1563 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1564 urlIsLoading = false;
1566 // Clear the cache and history if Incognito Mode is enabled.
1567 if (incognitoModeEnabled) {
1568 // Clear the cache. `true` includes disk files.
1569 mainWebView.clearCache(true);
1571 // Clear the back/forward history.
1572 mainWebView.clearHistory();
1574 // Manually delete cache folders.
1576 // Delete the main cache directory.
1577 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1579 // Delete the secondary `Service Worker` cache directory.
1580 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1581 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1582 } catch (IOException e) {
1583 // Do nothing if an error is thrown.
1587 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1588 if (!waitingForOrbot) {
1589 // Check to see if `WebView` has set `url` to be `about:blank`.
1590 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1591 // Set `formattedUrlString` to `""`.
1592 formattedUrlString = "";
1594 urlTextBox.setText(formattedUrlString);
1596 // Request focus for `urlTextBox`.
1597 urlTextBox.requestFocus();
1599 // Display the keyboard.
1600 inputMethodManager.showSoftInput(urlTextBox, 0);
1602 // Apply the domain settings. This clears any settings from the previous domain.
1603 applyDomainSettings(formattedUrlString, true, false);
1604 } else { // `WebView` has loaded a webpage.
1605 // Set `formattedUrlString`.
1606 formattedUrlString = url;
1608 // Only update `urlTextBox` if the user is not typing in it.
1609 if (!urlTextBox.hasFocus()) {
1610 // Display the formatted URL text.
1611 urlTextBox.setText(formattedUrlString);
1613 // Apply text highlighting to `urlTextBox`.
1618 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1619 sslCertificate = mainWebView.getCertificate();
1621 // 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.
1622 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1623 // Initialize the current SSL certificate variables.
1624 String currentWebsiteIssuedToCName = "";
1625 String currentWebsiteIssuedToOName = "";
1626 String currentWebsiteIssuedToUName = "";
1627 String currentWebsiteIssuedByCName = "";
1628 String currentWebsiteIssuedByOName = "";
1629 String currentWebsiteIssuedByUName = "";
1630 Date currentWebsiteSslStartDate = null;
1631 Date currentWebsiteSslEndDate = null;
1634 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1635 if (sslCertificate != null) {
1636 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1637 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1638 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1639 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1640 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1641 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1642 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1643 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1646 // 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`.
1647 String currentWebsiteSslStartDateString = "";
1648 String currentWebsiteSslEndDateString = "";
1649 String pinnedDomainSslStartDateString = "";
1650 String pinnedDomainSslEndDateString = "";
1652 // Convert the `Dates` to `Strings` if they are not `null`.
1653 if (currentWebsiteSslStartDate != null) {
1654 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1657 if (currentWebsiteSslEndDate != null) {
1658 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1661 if (pinnedDomainSslStartDate != null) {
1662 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1665 if (pinnedDomainSslEndDate != null) {
1666 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1669 // Check to see if the pinned SSL certificate matches the current website certificate.
1670 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1671 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1672 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1673 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1674 // The pinned SSL certificate doesn't match the current domain certificate.
1675 //Display the pinned SSL certificate mismatch `AlertDialog`.
1676 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1677 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1683 // Handle SSL Certificate errors.
1685 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1686 // Get the current website SSL certificate.
1687 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1689 // Extract the individual pieces of information from the current website SSL certificate.
1690 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1691 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1692 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1693 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1694 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1695 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1696 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1697 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1699 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1700 if (pinnedDomainSslCertificate &&
1701 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1702 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1703 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1704 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1705 // An SSL certificate is pinned and matches the current domain certificate.
1706 // Proceed to the website without displaying an error.
1708 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1709 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1710 sslErrorHandler = handler;
1712 // Display the SSL error `AlertDialog`.
1713 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1714 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1719 // Load the website if not waiting for Orbot to connect.
1720 if (!waitingForOrbot) {
1721 loadUrl(formattedUrlString);
1726 protected void onNewIntent(Intent intent) {
1727 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1730 // Check to see if the intent contains a new URL.
1731 if (intent.getData() != null) {
1732 // Get the intent data.
1733 final Uri intentUriData = intent.getData();
1735 // Load the website.
1736 loadUrl(intentUriData.toString());
1738 // Close the navigation drawer if it is open.
1739 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1740 drawerLayout.closeDrawer(GravityCompat.START);
1743 // Close the bookmarks drawer if it is open.
1744 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1745 drawerLayout.closeDrawer(GravityCompat.END);
1748 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1749 mainWebView.requestFocus();
1754 public void onRestart() {
1755 // Run the default commands.
1758 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1759 if (proxyThroughOrbot) {
1760 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1761 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1763 // Send the intent to the Orbot package.
1764 orbotIntent.setPackage("org.torproject.android");
1767 sendBroadcast(orbotIntent);
1770 // Apply the app settings if returning from the Settings activity..
1771 if (reapplyAppSettingsOnRestart) {
1772 // Apply the app settings.
1775 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1776 if (reloadOnRestart) {
1777 // Reload `mainWebView`.
1778 mainWebView.reload();
1780 // Reset `reloadOnRestartBoolean`.
1781 reloadOnRestart = false;
1784 // Reset the return from settings flag.
1785 reapplyAppSettingsOnRestart = false;
1788 // Apply the domain settings if returning from the Domains activity.
1789 if (reapplyDomainSettingsOnRestart) {
1790 // Reapply the domain settings.
1791 applyDomainSettings(formattedUrlString, false, true);
1793 // Reset `reapplyDomainSettingsOnRestart`.
1794 reapplyDomainSettingsOnRestart = false;
1797 // Load the URL on restart to apply changes to night mode.
1798 if (loadUrlOnRestart) {
1799 // Load the current `formattedUrlString`.
1800 loadUrl(formattedUrlString);
1802 // Reset `loadUrlOnRestart.
1803 loadUrlOnRestart = false;
1806 // Update the bookmarks drawer if returning from the Bookmarks activity.
1807 if (restartFromBookmarksActivity) {
1808 // Close the bookmarks drawer.
1809 drawerLayout.closeDrawer(GravityCompat.END);
1811 // Reload the bookmarks drawer.
1812 loadBookmarksFolder();
1814 // Reset `restartFromBookmarksActivity`.
1815 restartFromBookmarksActivity = false;
1818 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1819 updatePrivacyIcons(true);
1822 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1824 public void onResume() {
1825 // Run the default commands.
1828 // Resume JavaScript (if enabled).
1829 mainWebView.resumeTimers();
1831 // Resume `mainWebView`.
1832 mainWebView.onResume();
1834 // Resume the adView for the free flavor.
1835 if (BuildConfig.FLAVOR.contentEquals("free")) {
1837 AdHelper.resumeAd(findViewById(R.id.adview));
1840 // Display a message to the user if waiting for Orbot.
1841 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1842 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1843 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1846 if (displayingFullScreenVideo) {
1847 // Remove the translucent overlays.
1848 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1850 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1851 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1853 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1854 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1855 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1857 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1862 public void onPause() {
1863 // Run the default commands.
1866 // Pause `mainWebView`.
1867 mainWebView.onPause();
1869 // Stop all JavaScript.
1870 mainWebView.pauseTimers();
1872 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1873 if (BuildConfig.FLAVOR.contentEquals("free")) {
1875 AdHelper.pauseAd(findViewById(R.id.adview));
1880 public void onDestroy() {
1881 // Unregister the Orbot status broadcast receiver.
1882 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1884 // Run the default commands.
1889 public boolean onCreateOptionsMenu(Menu menu) {
1890 // Inflate the menu; this adds items to the action bar if it is present.
1891 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1893 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1896 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1897 updatePrivacyIcons(false);
1899 // Get handles for the menu items.
1900 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1901 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1902 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1903 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1904 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1905 refreshMenuItem = menu.findItem(R.id.refresh);
1906 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1908 // Only display third-party cookies if API >= 21
1909 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1911 // Only display the form data menu items if the API < 26.
1912 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1913 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1915 // Only show Ad Consent if this is the free flavor.
1916 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1918 // Get the shared preference values.
1919 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1921 // Get the status of the additional AppBar icons.
1922 displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1924 // 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.
1925 if (displayAdditionalAppBarIcons) {
1926 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1927 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1928 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1929 } else { //Do not display the additional icons.
1930 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1931 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1932 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1935 // Replace Refresh with Stop if a URL is already loading.
1938 refreshMenuItem.setTitle(R.string.stop);
1940 // If the icon is displayed in the AppBar, set it according to the theme.
1941 if (displayAdditionalAppBarIcons) {
1943 refreshMenuItem.setIcon(R.drawable.close_dark);
1945 refreshMenuItem.setIcon(R.drawable.close_light);
1954 public boolean onPrepareOptionsMenu(Menu menu) {
1955 // Get handles for the menu items.
1956 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1957 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1958 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1959 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1960 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1961 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1962 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1963 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1964 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1965 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1966 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1967 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1968 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1969 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1970 MenuItem blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1971 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1972 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1973 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1975 // Set the text for the domain menu item.
1976 if (domainSettingsApplied) {
1977 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1979 addOrEditDomain.setTitle(R.string.add_domain_settings);
1982 // Set the status of the menu item checkboxes.
1983 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1984 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1985 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1986 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
1987 easyListMenuItem.setChecked(easyListEnabled);
1988 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1989 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1990 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1991 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
1992 blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1993 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1994 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1996 // Enable third-party cookies if first-party cookies are enabled.
1997 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1999 // Enable DOM Storage if JavaScript is enabled.
2000 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2002 // Enable Clear Cookies if there are any.
2003 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2005 // Get a count of the number of files in the Local Storage directory.
2006 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2007 int localStorageDirectoryNumberOfFiles = 0;
2008 if (localStorageDirectory.exists()) {
2009 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2012 // Get a count of the number of files in the IndexedDB directory.
2013 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2014 int indexedDBDirectoryNumberOfFiles = 0;
2015 if (indexedDBDirectory.exists()) {
2016 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2019 // Enable Clear DOM Storage if there is any.
2020 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2022 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
2023 if (Build.VERSION.SDK_INT < 26) {
2024 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2025 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2027 // Disable clear form data because it is not supported on current version of Android.
2028 clearFormDataMenuItem.setEnabled(false);
2031 // Enable Clear Data if any of the submenu items are enabled.
2032 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2034 // Update the display names for the blocklists with the number of blocked requests.
2035 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2036 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2037 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2038 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2039 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2040 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2042 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2043 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2045 // Initialize font size variables.
2046 int fontSize = mainWebView.getSettings().getTextZoom();
2047 String fontSizeTitle;
2048 MenuItem selectedFontSizeMenuItem;
2050 // Prepare the font size title and current size menu item.
2053 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2054 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2058 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2059 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2063 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2064 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2068 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2069 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2073 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2074 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2078 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2079 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2083 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2084 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2088 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2089 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2093 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2094 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2098 // Set the font size title and select the current size menu item.
2099 fontSizeMenuItem.setTitle(fontSizeTitle);
2100 selectedFontSizeMenuItem.setChecked(true);
2102 // Run all the other default commands.
2103 super.onPrepareOptionsMenu(menu);
2105 // Display the menu.
2110 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2111 @SuppressLint("SetJavaScriptEnabled")
2112 // removeAllCookies is deprecated, but it is required for API < 21.
2113 @SuppressWarnings("deprecation")
2114 public boolean onOptionsItemSelected(MenuItem menuItem) {
2115 // Get the selected menu item ID.
2116 int menuItemId = menuItem.getItemId();
2118 // Set the commands that relate to the menu entries.
2119 switch (menuItemId) {
2120 case R.id.toggle_javascript:
2121 // Switch the status of javaScriptEnabled.
2122 javaScriptEnabled = !javaScriptEnabled;
2124 // Apply the new JavaScript status.
2125 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2127 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2128 updatePrivacyIcons(true);
2130 // Display a `Snackbar`.
2131 if (javaScriptEnabled) { // JavaScrip is enabled.
2132 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2133 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2134 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2135 } else { // Privacy mode.
2136 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2139 // Reload the WebView.
2140 mainWebView.reload();
2143 case R.id.add_or_edit_domain:
2144 if (domainSettingsApplied) { // Edit the current domain settings.
2145 // Reapply the domain settings on returning to `MainWebViewActivity`.
2146 reapplyDomainSettingsOnRestart = true;
2147 currentDomainName = "";
2149 // Create an intent to launch the domains activity.
2150 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2152 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2153 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2154 domainsIntent.putExtra("closeOnBack", true);
2157 startActivity(domainsIntent);
2158 } else { // Add a new domain.
2159 // Apply the new domain settings on returning to `MainWebViewActivity`.
2160 reapplyDomainSettingsOnRestart = true;
2161 currentDomainName = "";
2163 // Get the current domain
2164 Uri currentUri = Uri.parse(formattedUrlString);
2165 String currentDomain = currentUri.getHost();
2167 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2168 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2170 // Create the domain and store the database ID.
2171 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2173 // Create an intent to launch the domains activity.
2174 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2176 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2177 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2178 domainsIntent.putExtra("closeOnBack", true);
2181 startActivity(domainsIntent);
2185 case R.id.toggle_first_party_cookies:
2186 // Switch the status of firstPartyCookiesEnabled.
2187 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2189 // Update the menu checkbox.
2190 menuItem.setChecked(firstPartyCookiesEnabled);
2192 // Apply the new cookie status.
2193 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2195 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2196 updatePrivacyIcons(true);
2198 // Display a `Snackbar`.
2199 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2200 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2201 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2202 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2203 } else { // Privacy mode.
2204 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2207 // Reload the WebView.
2208 mainWebView.reload();
2211 case R.id.toggle_third_party_cookies:
2212 if (Build.VERSION.SDK_INT >= 21) {
2213 // Switch the status of thirdPartyCookiesEnabled.
2214 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2216 // Update the menu checkbox.
2217 menuItem.setChecked(thirdPartyCookiesEnabled);
2219 // Apply the new cookie status.
2220 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2222 // Display a `Snackbar`.
2223 if (thirdPartyCookiesEnabled) {
2224 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2226 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2229 // Reload the WebView.
2230 mainWebView.reload();
2231 } // Else do nothing because SDK < 21.
2234 case R.id.toggle_dom_storage:
2235 // Switch the status of domStorageEnabled.
2236 domStorageEnabled = !domStorageEnabled;
2238 // Update the menu checkbox.
2239 menuItem.setChecked(domStorageEnabled);
2241 // Apply the new DOM Storage status.
2242 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2244 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2245 updatePrivacyIcons(true);
2247 // Display a `Snackbar`.
2248 if (domStorageEnabled) {
2249 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2251 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2254 // Reload the WebView.
2255 mainWebView.reload();
2258 // Form data can be removed once the minimum API >= 26.
2259 case R.id.toggle_save_form_data:
2260 // Switch the status of saveFormDataEnabled.
2261 saveFormDataEnabled = !saveFormDataEnabled;
2263 // Update the menu checkbox.
2264 menuItem.setChecked(saveFormDataEnabled);
2266 // Apply the new form data status.
2267 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2269 // Display a `Snackbar`.
2270 if (saveFormDataEnabled) {
2271 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2273 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2276 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2277 updatePrivacyIcons(true);
2279 // Reload the WebView.
2280 mainWebView.reload();
2283 case R.id.clear_cookies:
2284 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2285 .setAction(R.string.undo, v -> {
2286 // Do nothing because everything will be handled by `onDismissed()` below.
2288 .addCallback(new Snackbar.Callback() {
2290 public void onDismissed(Snackbar snackbar, int event) {
2292 // The user pushed the `Undo` button.
2293 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2297 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2299 // `cookieManager.removeAllCookie()` varies by SDK.
2300 if (Build.VERSION.SDK_INT < 21) {
2301 cookieManager.removeAllCookie();
2303 // `null` indicates no callback.
2304 cookieManager.removeAllCookies(null);
2312 case R.id.clear_dom_storage:
2313 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2314 .setAction(R.string.undo, v -> {
2315 // Do nothing because everything will be handled by `onDismissed()` below.
2317 .addCallback(new Snackbar.Callback() {
2319 public void onDismissed(Snackbar snackbar, int event) {
2321 // The user pushed the `Undo` button.
2322 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2326 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2328 // Delete the DOM Storage.
2329 WebStorage webStorage = WebStorage.getInstance();
2330 webStorage.deleteAllData();
2332 // Manually delete the DOM storage files and directories.
2334 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2335 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2337 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2338 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2339 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2340 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2341 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2342 } catch (IOException e) {
2343 // Do nothing if an error is thrown.
2351 // Form data can be remove once the minimum API >= 26.
2352 case R.id.clear_form_data:
2353 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2354 .setAction(R.string.undo, v -> {
2355 // Do nothing because everything will be handled by `onDismissed()` below.
2357 .addCallback(new Snackbar.Callback() {
2359 public void onDismissed(Snackbar snackbar, int event) {
2361 // The user pushed the `Undo` button.
2362 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2366 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2368 // Delete the form data.
2369 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2370 mainWebViewDatabase.clearFormData();
2377 case R.id.font_size_twenty_five_percent:
2378 mainWebView.getSettings().setTextZoom(25);
2381 case R.id.font_size_fifty_percent:
2382 mainWebView.getSettings().setTextZoom(50);
2385 case R.id.font_size_seventy_five_percent:
2386 mainWebView.getSettings().setTextZoom(75);
2389 case R.id.font_size_one_hundred_percent:
2390 mainWebView.getSettings().setTextZoom(100);
2393 case R.id.font_size_one_hundred_twenty_five_percent:
2394 mainWebView.getSettings().setTextZoom(125);
2397 case R.id.font_size_one_hundred_fifty_percent:
2398 mainWebView.getSettings().setTextZoom(150);
2401 case R.id.font_size_one_hundred_seventy_five_percent:
2402 mainWebView.getSettings().setTextZoom(175);
2405 case R.id.font_size_two_hundred_percent:
2406 mainWebView.getSettings().setTextZoom(200);
2409 case R.id.swipe_to_refresh:
2410 // Toggle swipe to refresh.
2411 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2414 case R.id.display_images:
2415 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2416 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2417 mainWebView.reload();
2418 } else { // Images are not currently loaded automatically.
2419 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2422 // Set `onTheFlyDisplayImagesSet`.
2423 onTheFlyDisplayImagesSet = true;
2426 case R.id.view_source:
2427 // Launch the View Source activity.
2428 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2429 startActivity(viewSourceIntent);
2433 // Toggle the EasyList status.
2434 easyListEnabled = !easyListEnabled;
2436 // Update the menu checkbox.
2437 menuItem.setChecked(easyListEnabled);
2439 // Reload the main WebView.
2440 mainWebView.reload();
2443 case R.id.easyprivacy:
2444 // Toggle the EasyPrivacy status.
2445 easyPrivacyEnabled = !easyPrivacyEnabled;
2447 // Update the menu checkbox.
2448 menuItem.setChecked(easyPrivacyEnabled);
2450 // Reload the main WebView.
2451 mainWebView.reload();
2454 case R.id.fanboys_annoyance_list:
2455 // Toggle Fanboy's Annoyance List status.
2456 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2458 // Update the menu checkbox.
2459 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2461 // Update the staus of Fanboy's Social Blocking List.
2462 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2463 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2465 // Reload the main WebView.
2466 mainWebView.reload();
2469 case R.id.fanboys_social_blocking_list:
2470 // Toggle Fanboy's Social Blocking List status.
2471 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2473 // Update the menu checkbox.
2474 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2476 // Reload the main WebView.
2477 mainWebView.reload();
2480 case R.id.ultraprivacy:
2481 // Toggle the UltraPrivacy status.
2482 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2484 // Update the menu checkbox.
2485 menuItem.setChecked(ultraPrivacyEnabled);
2487 // Reload the main WebView.
2488 mainWebView.reload();
2491 case R.id.block_all_third_party_requests:
2492 //Toggle the third-party requests blocker status.
2493 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2495 // Update the menu checkbox.
2496 menuItem.setChecked(blockAllThirdPartyRequests);
2498 // Reload the main WebView.
2499 mainWebView.reload();
2503 // Setup the share string.
2504 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2506 // Create the share intent.
2507 Intent shareIntent = new Intent();
2508 shareIntent.setAction(Intent.ACTION_SEND);
2509 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2510 shareIntent.setType("text/plain");
2513 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2516 case R.id.find_on_page:
2517 // Hide the URL app bar.
2518 supportAppBar.setVisibility(View.GONE);
2520 // Show the Find on Page `RelativeLayout`.
2521 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2523 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2524 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2525 findOnPageEditText.postDelayed(() -> {
2526 // Set the focus on `findOnPageEditText`.
2527 findOnPageEditText.requestFocus();
2529 // Display the keyboard. `0` sets no input flags.
2530 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2535 // Get a `PrintManager` instance.
2536 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2538 // Convert `mainWebView` to `printDocumentAdapter`.
2539 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2541 // Remove the lint error below that `printManager` might be `null`.
2542 assert printManager != null;
2544 // Print the document. The print attributes are `null`.
2545 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2548 case R.id.add_to_homescreen:
2549 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2550 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2551 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2553 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2557 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2558 // Reload the WebView.
2559 mainWebView.reload();
2560 } else { // The stop button was pushed.
2561 // Stop the loading of the WebView.
2562 mainWebView.stopLoading();
2566 case R.id.ad_consent:
2567 // Display the ad consent dialog.
2568 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2569 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2573 // Don't consume the event.
2574 return super.onOptionsItemSelected(menuItem);
2578 // removeAllCookies is deprecated, but it is required for API < 21.
2579 @SuppressWarnings("deprecation")
2581 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2582 int menuItemId = menuItem.getItemId();
2584 switch (menuItemId) {
2590 if (mainWebView.canGoBack()) {
2591 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2592 formattedUrlString = "";
2594 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2595 navigatingHistory = true;
2597 // Load the previous website in the history.
2598 mainWebView.goBack();
2603 if (mainWebView.canGoForward()) {
2604 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2605 formattedUrlString = "";
2607 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2608 navigatingHistory = true;
2610 // Load the next website in the history.
2611 mainWebView.goForward();
2616 // Get the `WebBackForwardList`.
2617 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2619 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2620 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2621 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2625 // Launch the requests activity.
2626 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2627 startActivity(requestsIntent);
2630 case R.id.downloads:
2631 // Launch the system Download Manager.
2632 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2634 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2635 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2637 startActivity(downloadManagerIntent);
2641 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2642 reapplyDomainSettingsOnRestart = true;
2643 currentDomainName = "";
2645 // Launch the domains activity.
2646 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2647 startActivity(domainsIntent);
2651 // Set the flag to reapply app settings on restart when returning from Settings.
2652 reapplyAppSettingsOnRestart = true;
2654 // Set the flag to reapply the domain settings on restart when returning from Settings.
2655 reapplyDomainSettingsOnRestart = true;
2656 currentDomainName = "";
2658 // Launch the settings activity.
2659 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2660 startActivity(settingsIntent);
2664 // Launch `GuideActivity`.
2665 Intent guideIntent = new Intent(this, GuideActivity.class);
2666 startActivity(guideIntent);
2670 // Launch `AboutActivity`.
2671 Intent aboutIntent = new Intent(this, AboutActivity.class);
2672 startActivity(aboutIntent);
2675 case R.id.clearAndExit:
2676 // Get a handle for `sharedPreferences`. `this` references the current context.
2677 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2679 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2682 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2683 // The command to remove cookies changed slightly in API 21.
2684 if (Build.VERSION.SDK_INT >= 21) {
2685 cookieManager.removeAllCookies(null);
2687 cookieManager.removeAllCookie();
2690 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2692 // We have to use two commands because `Runtime.exec()` does not like `*`.
2693 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2694 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2695 } catch (IOException e) {
2696 // Do nothing if an error is thrown.
2700 // Clear DOM storage.
2701 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2702 // Ask `WebStorage` to clear the DOM storage.
2703 WebStorage webStorage = WebStorage.getInstance();
2704 webStorage.deleteAllData();
2706 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2708 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2709 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2711 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2712 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2713 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2714 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2715 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2716 } catch (IOException e) {
2717 // Do nothing if an error is thrown.
2721 // Clear form data if the API < 26.
2722 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2723 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2724 webViewDatabase.clearFormData();
2726 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2728 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2729 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2730 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2731 } catch (IOException e) {
2732 // Do nothing if an error is thrown.
2737 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2738 // `true` includes disk files.
2739 mainWebView.clearCache(true);
2741 // Manually delete the cache directories.
2743 // Delete the main cache directory.
2744 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2746 // Delete the secondary `Service Worker` cache directory.
2747 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2748 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2749 } catch (IOException e) {
2750 // Do nothing if an error is thrown.
2754 // Clear SSL certificate preferences.
2755 mainWebView.clearSslPreferences();
2757 // Clear the back/forward history.
2758 mainWebView.clearHistory();
2760 // Clear `formattedUrlString`.
2761 formattedUrlString = null;
2763 // Clear `customHeaders`.
2764 customHeaders.clear();
2766 // Detach all views from `mainWebViewRelativeLayout`.
2767 mainWebViewRelativeLayout.removeAllViews();
2769 // Destroy the internal state of `mainWebView`.
2770 mainWebView.destroy();
2772 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2773 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2774 if (clearEverything) {
2776 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2777 } catch (IOException e) {
2778 // Do nothing if an error is thrown.
2782 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2783 if (Build.VERSION.SDK_INT >= 21) {
2784 finishAndRemoveTask();
2789 // Remove the terminated program from RAM. The status code is `0`.
2794 // Close the navigation drawer.
2795 drawerLayout.closeDrawer(GravityCompat.START);
2800 public void onPostCreate(Bundle savedInstanceState) {
2801 super.onPostCreate(savedInstanceState);
2803 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2804 drawerToggle.syncState();
2808 public void onConfigurationChanged(Configuration newConfig) {
2809 super.onConfigurationChanged(newConfig);
2811 // Reload the ad for the free flavor if we not in full screen mode.
2812 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2813 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2814 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2817 // `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:
2818 // https://code.google.com/p/android/issues/detail?id=20493#c8
2819 // ActivityCompat.invalidateOptionsMenu(this);
2823 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2824 // Store the `HitTestResult`.
2825 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2828 final String imageUrl;
2829 final String linkUrl;
2831 // Get a handle for the `ClipboardManager`.
2832 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2834 // Remove the lint errors below that `clipboardManager` might be `null`.
2835 assert clipboardManager != null;
2837 switch (hitTestResult.getType()) {
2838 // `SRC_ANCHOR_TYPE` is a link.
2839 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2840 // Get the target URL.
2841 linkUrl = hitTestResult.getExtra();
2843 // Set the target URL as the title of the `ContextMenu`.
2844 menu.setHeaderTitle(linkUrl);
2846 // Add a Load URL entry.
2847 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2852 // Add a Copy URL entry.
2853 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2854 // Save the link URL in a `ClipData`.
2855 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2857 // Set the `ClipData` as the clipboard's primary clip.
2858 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2862 // Add a Download URL entry.
2863 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2864 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2865 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2866 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2868 // Store the variables for future use by `onRequestPermissionsResult()`.
2869 downloadUrl = linkUrl;
2870 downloadContentDisposition = "none";
2871 downloadContentLength = -1;
2873 // Show a dialog if the user has previously denied the permission.
2874 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2875 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2876 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2878 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2879 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2880 } else { // Show the permission request directly.
2881 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2882 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2884 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2885 // Get a handle for the download file alert dialog.
2886 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2888 // Show the download file alert dialog.
2889 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2894 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2895 menu.add(R.string.cancel);
2898 case WebView.HitTestResult.EMAIL_TYPE:
2899 // Get the target URL.
2900 linkUrl = hitTestResult.getExtra();
2902 // Set the target URL as the title of the `ContextMenu`.
2903 menu.setHeaderTitle(linkUrl);
2905 // Add a `Write Email` entry.
2906 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2907 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2908 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2910 // Parse the url and set it as the data for the `Intent`.
2911 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2913 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2914 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2917 startActivity(emailIntent);
2921 // Add a `Copy Email Address` entry.
2922 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2923 // Save the email address in a `ClipData`.
2924 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2926 // Set the `ClipData` as the clipboard's primary clip.
2927 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2931 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2932 menu.add(R.string.cancel);
2935 // `IMAGE_TYPE` is an image.
2936 case WebView.HitTestResult.IMAGE_TYPE:
2937 // Get the image URL.
2938 imageUrl = hitTestResult.getExtra();
2940 // Set the image URL as the title of the `ContextMenu`.
2941 menu.setHeaderTitle(imageUrl);
2943 // Add a `View Image` entry.
2944 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2949 // Add a `Download Image` entry.
2950 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2951 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2952 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2953 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2955 // Store the image URL for use by `onRequestPermissionResult()`.
2956 downloadImageUrl = imageUrl;
2958 // Show a dialog if the user has previously denied the permission.
2959 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2960 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2961 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2963 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2964 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2965 } else { // Show the permission request directly.
2966 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2967 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2969 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2970 // Get a handle for the download image alert dialog.
2971 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2973 // Show the download image alert dialog.
2974 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2979 // Add a `Copy URL` entry.
2980 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2981 // Save the image URL in a `ClipData`.
2982 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2984 // Set the `ClipData` as the clipboard's primary clip.
2985 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2989 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2990 menu.add(R.string.cancel);
2994 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2995 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2996 // Get the image URL.
2997 imageUrl = hitTestResult.getExtra();
2999 // Set the image URL as the title of the `ContextMenu`.
3000 menu.setHeaderTitle(imageUrl);
3002 // Add a `View Image` entry.
3003 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3008 // Add a `Download Image` entry.
3009 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3010 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3011 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3012 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3014 // Store the image URL for use by `onRequestPermissionResult()`.
3015 downloadImageUrl = imageUrl;
3017 // Show a dialog if the user has previously denied the permission.
3018 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3019 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3020 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3022 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3023 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3024 } else { // Show the permission request directly.
3025 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3026 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3028 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3029 // Get a handle for the download image alert dialog.
3030 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3032 // Show the download image alert dialog.
3033 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3038 // Add a `Copy URL` entry.
3039 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3040 // Save the image URL in a `ClipData`.
3041 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3043 // Set the `ClipData` as the clipboard's primary clip.
3044 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3048 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3049 menu.add(R.string.cancel);
3055 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3056 // Get the `EditTexts` from the `dialogFragment`.
3057 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3058 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3060 // Extract the strings from the `EditTexts`.
3061 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3062 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3064 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3065 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3066 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3067 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3069 // Display the new bookmark below the current items in the (0 indexed) list.
3070 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3072 // Create the bookmark.
3073 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3075 // Update `bookmarksCursor` with the current contents of this folder.
3076 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3078 // Update the `ListView`.
3079 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3081 // Scroll to the new bookmark.
3082 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3086 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3087 // Get handles for the views in `dialogFragment`.
3088 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3089 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3090 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3092 // Get new folder name string.
3093 String folderNameString = createFolderNameEditText.getText().toString();
3095 // Get the new folder icon `Bitmap`.
3096 Bitmap folderIconBitmap;
3097 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3098 // Get the default folder icon and convert it to a `Bitmap`.
3099 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3100 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3101 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3102 } else { // Use the `WebView` favorite icon.
3103 folderIconBitmap = favoriteIconBitmap;
3106 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3107 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3108 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3109 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3111 // Move all the bookmarks down one in the display order.
3112 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3113 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3114 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3117 // Create the folder, which will be placed at the top of the `ListView`.
3118 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3120 // Update `bookmarksCursor` with the current contents of this folder.
3121 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3123 // Update the `ListView`.
3124 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3126 // Scroll to the new folder.
3127 bookmarksListView.setSelection(0);
3131 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3132 // Get the shortcut name.
3133 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3134 String shortcutNameString = shortcutNameEditText.getText().toString();
3136 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3137 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3139 // Setup the shortcut intent.
3140 Intent shortcutIntent = new Intent();
3141 shortcutIntent.setAction(Intent.ACTION_VIEW);
3142 shortcutIntent.setData(Uri.parse(formattedUrlString));
3144 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3145 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3147 // Add the required fields to the shortcut info builder.
3148 shortcutInfoBuilder.setIcon(favoriteIcon);
3149 shortcutInfoBuilder.setIntent(shortcutIntent);
3150 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3152 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3153 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3157 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3158 switch (downloadType) {
3159 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3160 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3161 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3164 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3165 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3166 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3172 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
3173 switch (requestCode) {
3174 case DOWNLOAD_FILE_REQUEST_CODE:
3175 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3176 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3178 // On API 23, displaying the fragment must be delayed or the app will crash.
3179 if (Build.VERSION.SDK_INT == 23) {
3180 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3182 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3185 // Reset the download variables.
3187 downloadContentDisposition = "";
3188 downloadContentLength = 0;
3191 case DOWNLOAD_IMAGE_REQUEST_CODE:
3192 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3193 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3195 // On API 23, displaying the fragment must be delayed or the app will crash.
3196 if (Build.VERSION.SDK_INT == 23) {
3197 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3199 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3202 // Reset the image URL variable.
3203 downloadImageUrl = "";
3209 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3210 // Download the image if it has an HTTP or HTTPS URI.
3211 if (imageUrl.startsWith("http")) {
3212 // Get a handle for the system `DOWNLOAD_SERVICE`.
3213 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3215 // Parse `imageUrl`.
3216 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3218 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3219 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3220 if (firstPartyCookiesEnabled) {
3221 // Get the cookies for `imageUrl`.
3222 String cookies = cookieManager.getCookie(imageUrl);
3224 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3225 downloadRequest.addRequestHeader("Cookie", cookies);
3228 // Get the file name from the dialog fragment.
3229 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3230 String imageName = downloadImageNameEditText.getText().toString();
3232 // Specify the download location.
3233 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3234 // Download to the public download directory.
3235 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3236 } else { // External write permission denied.
3237 // Download to the app's external download directory.
3238 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3241 // Allow `MediaScanner` to index the download if it is a media file.
3242 downloadRequest.allowScanningByMediaScanner();
3244 // Add the URL as the description for the download.
3245 downloadRequest.setDescription(imageUrl);
3247 // Show the download notification after the download is completed.
3248 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3250 // Remove the lint warning below that `downloadManager` might be `null`.
3251 assert downloadManager != null;
3253 // Initiate the download.
3254 downloadManager.enqueue(downloadRequest);
3255 } else { // The image is not an HTTP or HTTPS URI.
3256 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3261 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3262 // Download the file if it has an HTTP or HTTPS URI.
3263 if (downloadUrl.startsWith("http")) {
3264 // Get a handle for the system `DOWNLOAD_SERVICE`.
3265 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3267 // Parse `downloadUrl`.
3268 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3270 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3271 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3272 if (firstPartyCookiesEnabled) {
3273 // Get the cookies for `downloadUrl`.
3274 String cookies = cookieManager.getCookie(downloadUrl);
3276 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3277 downloadRequest.addRequestHeader("Cookie", cookies);
3280 // Get the file name from the dialog fragment.
3281 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3282 String fileName = downloadFileNameEditText.getText().toString();
3284 // Specify the download location.
3285 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3286 // Download to the public download directory.
3287 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3288 } else { // External write permission denied.
3289 // Download to the app's external download directory.
3290 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3293 // Allow `MediaScanner` to index the download if it is a media file.
3294 downloadRequest.allowScanningByMediaScanner();
3296 // Add the URL as the description for the download.
3297 downloadRequest.setDescription(downloadUrl);
3299 // Show the download notification after the download is completed.
3300 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3302 // Remove the lint warning below that `downloadManager` might be `null`.
3303 assert downloadManager != null;
3305 // Initiate the download.
3306 downloadManager.enqueue(downloadRequest);
3307 } else { // The download is not an HTTP or HTTPS URI.
3308 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3313 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3314 // Get handles for the views from `dialogFragment`.
3315 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3316 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3317 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3319 // Store the bookmark strings.
3320 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3321 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3323 // Update the bookmark.
3324 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3325 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3326 } else { // Update the bookmark using the `WebView` favorite icon.
3327 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3328 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3329 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3330 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3332 // Update the bookmark and the favorite icon.
3333 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3336 // Update `bookmarksCursor` with the current contents of this folder.
3337 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3339 // Update the `ListView`.
3340 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3344 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3345 // Get handles for the views from `dialogFragment`.
3346 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3347 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3348 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3349 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3351 // Get the new folder name.
3352 String newFolderNameString = editFolderNameEditText.getText().toString();
3354 // Check if the favorite icon has changed.
3355 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3356 // Update the name in the database.
3357 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3358 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3359 // Get the new folder icon `Bitmap`.
3360 Bitmap folderIconBitmap;
3361 if (defaultFolderIconRadioButton.isChecked()) {
3362 // Get the default folder icon and convert it to a `Bitmap`.
3363 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3364 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3365 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3366 } else { // Use the `WebView` favorite icon.
3367 folderIconBitmap = favoriteIconBitmap;
3370 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3371 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3372 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3373 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3375 // Update the folder icon in the database.
3376 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3377 } else { // The folder icon and the name have changed.
3378 // Get the new folder icon `Bitmap`.
3379 Bitmap folderIconBitmap;
3380 if (defaultFolderIconRadioButton.isChecked()) {
3381 // Get the default folder icon and convert it to a `Bitmap`.
3382 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3383 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3384 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3385 } else { // Use the `WebView` favorite icon.
3386 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3389 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3390 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3391 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3392 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3394 // Update the folder name and icon in the database.
3395 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3398 // Update `bookmarksCursor` with the current contents of this folder.
3399 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3401 // Update the `ListView`.
3402 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3406 public void onHttpAuthenticationCancel() {
3407 // Cancel the `HttpAuthHandler`.
3408 httpAuthHandler.cancel();
3412 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3413 // Get handles for the `EditTexts`.
3414 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3415 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3417 // Proceed with the HTTP authentication.
3418 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3421 public void viewSslCertificate(View view) {
3422 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3423 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3424 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3428 public void onSslErrorCancel() {
3429 sslErrorHandler.cancel();
3433 public void onSslErrorProceed() {
3434 sslErrorHandler.proceed();
3438 public void onSslMismatchBack() {
3439 if (mainWebView.canGoBack()) { // There is a back page in the history.
3440 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3441 formattedUrlString = "";
3443 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3444 navigatingHistory = true;
3447 mainWebView.goBack();
3448 } else { // There are no pages to go back to.
3449 // Load a blank page
3455 public void onSslMismatchProceed() {
3456 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3457 ignorePinnedSslCertificate = true;
3461 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3462 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3463 formattedUrlString = "";
3465 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3466 navigatingHistory = true;
3468 // Load the history entry.
3469 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3473 public void onClearHistory() {
3474 // Clear the history.
3475 mainWebView.clearHistory();
3478 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3480 public void onBackPressed() {
3481 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3482 // Close the navigation drawer.
3483 drawerLayout.closeDrawer(GravityCompat.START);
3484 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3485 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3486 // close the bookmarks drawer.
3487 drawerLayout.closeDrawer(GravityCompat.END);
3488 } else { // A subfolder is displayed.
3489 // Place the former parent folder in `currentFolder`.
3490 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3492 // Load the new folder.
3493 loadBookmarksFolder();
3496 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3497 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3498 formattedUrlString = "";
3500 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3501 navigatingHistory = true;
3504 mainWebView.goBack();
3505 } else { // There isn't anything to do in Privacy Browser.
3506 // Pass `onBackPressed()` to the system.
3507 super.onBackPressed();
3511 // 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.
3513 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3514 // File uploads only work on API >= 21.
3515 if (Build.VERSION.SDK_INT >= 21) {
3516 // Pass the file to the WebView.
3517 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3521 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3522 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3523 String unformattedUrlString = urlTextBox.getText().toString().trim();
3525 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3526 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3527 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3528 if (!unformattedUrlString.startsWith("http")) {
3529 unformattedUrlString = "http://" + unformattedUrlString;
3532 // Initialize `unformattedUrl`.
3533 URL unformattedUrl = null;
3535 // 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.
3537 unformattedUrl = new URL(unformattedUrlString);
3538 } catch (MalformedURLException e) {
3539 e.printStackTrace();
3542 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3543 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3544 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3545 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3546 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3547 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3550 Uri.Builder formattedUri = new Uri.Builder();
3551 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3553 // Decode `formattedUri` as a `String` in `UTF-8`.
3554 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3555 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3556 // Load a blank string.
3557 formattedUrlString = "";
3558 } else { // Search for the contents of the URL box.
3559 // Sanitize the search input and convert it to a search.
3560 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3562 // Add the base search URL.
3563 formattedUrlString = searchURL + encodedUrlString;
3566 // 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.
3567 urlTextBox.clearFocus();
3570 loadUrl(formattedUrlString);
3573 private void loadUrl(String url) {// Apply any custom domain settings.
3574 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3575 formattedUrlString = url;
3577 // Apply the domain settings.
3578 applyDomainSettings(url, true, false);
3580 // If loading a website, set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3581 urlIsLoading = !url.equals("");
3584 mainWebView.loadUrl(url, customHeaders);
3587 public void findPreviousOnPage(View view) {
3588 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3589 mainWebView.findNext(false);
3592 public void findNextOnPage(View view) {
3593 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3594 mainWebView.findNext(true);
3597 public void closeFindOnPage(View view) {
3598 // Delete the contents of `find_on_page_edittext`.
3599 findOnPageEditText.setText(null);
3601 // Clear the highlighted phrases.
3602 mainWebView.clearMatches();
3604 // Hide the Find on Page `RelativeLayout`.
3605 findOnPageLinearLayout.setVisibility(View.GONE);
3607 // Show the URL app bar.
3608 supportAppBar.setVisibility(View.VISIBLE);
3610 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3611 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3614 private void applyAppSettings() {
3615 // Get a handle for the shared preferences.
3616 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3618 // Store the values from the shared preferences in variables.
3619 String homepageString = sharedPreferences.getString("homepage", "https://searx.me/");
3620 String torHomepageString = sharedPreferences.getString("tor_homepage", "http://ulrn6sryqaifefld.onion/");
3621 String torSearchString = sharedPreferences.getString("tor_search", "http://ulrn6sryqaifefld.onion/?q=");
3622 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3623 String searchString = sharedPreferences.getString("search", "https://searx.me/?q=");
3624 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3625 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3626 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3627 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3628 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3629 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3630 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3631 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3633 // Set the homepage, search, and proxy options.
3634 if (proxyThroughOrbot) { // Set the Tor options.
3635 // Set `torHomepageString` as `homepage`.
3636 homepage = torHomepageString;
3638 // If formattedUrlString is null assign the homepage to it.
3639 if (formattedUrlString == null) {
3640 formattedUrlString = homepage;
3643 // Set the search URL.
3644 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3645 searchURL = torSearchCustomURLString;
3646 } else { // Use the string from the pre-built list.
3647 searchURL = torSearchString;
3650 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3651 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3653 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3655 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3657 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3660 // Display a message to the user if waiting for Orbot.
3661 if (!orbotStatus.equals("ON")) {
3662 // Set `waitingForOrbot`.
3663 waitingForOrbot = true;
3665 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3666 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3668 } else { // Set the non-Tor options.
3669 // Set `homepageString` as `homepage`.
3670 homepage = homepageString;
3672 // If formattedUrlString is null assign the homepage to it.
3673 if (formattedUrlString == null) {
3674 formattedUrlString = homepage;
3677 // Set the search URL.
3678 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3679 searchURL = searchCustomURLString;
3680 } else { // Use the string from the pre-built list.
3681 searchURL = searchString;
3684 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3685 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3687 // Set the default `appBar` background. `this` refers to the context.
3689 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3691 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3694 // Reset `waitingForOrbot.
3695 waitingForOrbot = false;
3698 // Set Do Not Track status.
3699 if (doNotTrackEnabled) {
3700 customHeaders.put("DNT", "1");
3702 customHeaders.remove("DNT");
3705 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3706 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3707 if (hideSystemBarsOnFullscreen) { // Hide everything.
3708 // Remove the translucent navigation setting if it is currently flagged.
3709 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3711 // Remove the translucent status bar overlay.
3712 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3714 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3715 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3717 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3718 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3719 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3721 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3722 } else { // Hide everything except the status and navigation bars.
3723 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3724 rootCoordinatorLayout.setSystemUiVisibility(0);
3726 // Add the translucent status flag if it is unset.
3727 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3729 if (translucentNavigationBarOnFullscreen) {
3730 // Set the navigation bar to be translucent.
3731 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3733 // Set the navigation bar to be black.
3734 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3737 } else { // Privacy Browser is not in full screen browsing mode.
3738 // 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.
3739 inFullScreenBrowsingMode = false;
3741 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3742 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3746 // Show the `BannerAd` in the free flavor.
3747 if (BuildConfig.FLAVOR.contentEquals("free")) {
3748 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3749 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3752 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3753 rootCoordinatorLayout.setSystemUiVisibility(0);
3755 // Remove the translucent navigation bar flag if it is set.
3756 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3758 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3759 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3761 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3762 rootCoordinatorLayout.setFitsSystemWindows(true);
3766 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3767 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3768 @SuppressWarnings("deprecation")
3769 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3770 // Parse the URL into a URI.
3771 Uri uri = Uri.parse(url);
3773 // Extract the domain from `uri`.
3774 String hostName = uri.getHost();
3776 // Initialize `loadingNewDomainName`.
3777 boolean loadingNewDomainName;
3779 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3780 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3781 //noinspection SimplifiableIfStatement
3782 if ((hostName == null) || (currentDomainName == null)) {
3783 loadingNewDomainName = true;
3784 } else { // Determine if `hostName` equals `currentDomainName`.
3785 loadingNewDomainName = !hostName.equals(currentDomainName);
3788 // Strings don't like to be null.
3789 if (hostName == null) {
3793 // 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.
3794 if (loadingNewDomainName) {
3795 // Set the new `hostname` as the `currentDomainName`.
3796 currentDomainName = hostName;
3798 // Reset `ignorePinnedSslCertificate`.
3799 ignorePinnedSslCertificate = false;
3801 // Reset the favorite icon if specified.
3802 if (resetFavoriteIcon) {
3803 favoriteIconBitmap = favoriteIconDefaultBitmap;
3804 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3807 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3808 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3809 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3811 // Get a full cursor from `domainsDatabaseHelper`.
3812 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3814 // Initialize `domainSettingsSet`.
3815 Set<String> domainSettingsSet = new HashSet<>();
3817 // Get the domain name column index.
3818 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3820 // Populate `domainSettingsSet`.
3821 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3822 // Move `domainsCursor` to the current row.
3823 domainNameCursor.moveToPosition(i);
3825 // Store the domain name in `domainSettingsSet`.
3826 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3829 // Close `domainNameCursor.
3830 domainNameCursor.close();
3832 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3833 domainSettingsApplied = false;
3834 String domainNameInDatabase = null;
3836 // Check the hostname.
3837 if (domainSettingsSet.contains(hostName)) {
3838 domainSettingsApplied = true;
3839 domainNameInDatabase = hostName;
3842 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3843 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3844 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3845 // Apply the domain settings.
3846 domainSettingsApplied = true;
3848 // Store the applied domain names as it appears in the database.
3849 domainNameInDatabase = "*." + hostName;
3852 // Strip out the lowest subdomain of of the host name.
3853 hostName = hostName.substring(hostName.indexOf(".") + 1);
3857 // Get a handle for the shared preference.
3858 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3860 // Store the general preference information.
3861 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3862 String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3863 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3864 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3865 nightMode = sharedPreferences.getBoolean("night_mode", false);
3867 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3868 // Get a cursor for the current host and move it to the first position.
3869 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3870 currentHostDomainSettingsCursor.moveToFirst();
3872 // Get the settings from the cursor.
3873 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3874 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3875 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3876 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3877 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3878 // Form data can be removed once the minimum API >= 26.
3879 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3880 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3881 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3882 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3883 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3884 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3885 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3886 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3887 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3888 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3889 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3890 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3891 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3892 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3893 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3894 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3895 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3896 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3897 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3899 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3900 switch (nightModeInt) {
3901 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3905 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3910 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3912 javaScriptEnabled = true;
3915 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3916 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3917 pinnedDomainSslStartDate = null;
3919 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3922 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3923 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3924 pinnedDomainSslEndDate = null;
3926 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3929 // Close `currentHostDomainSettingsCursor`.
3930 currentHostDomainSettingsCursor.close();
3932 // Apply the domain settings.
3933 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3934 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3935 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3937 // Apply the form data setting if the API < 26.
3938 if (Build.VERSION.SDK_INT < 26) {
3939 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3942 // Apply the font size.
3943 if (fontSize == 0) { // Apply the default font size.
3944 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3945 } else { // Apply the specified font size.
3946 mainWebView.getSettings().setTextZoom(fontSize);
3949 // Set third-party cookies status if API >= 21.
3950 if (Build.VERSION.SDK_INT >= 21) {
3951 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3954 // 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.
3955 // <https://redmine.stoutner.com/issues/160>
3956 if (!urlIsLoading) {
3957 // Set the user agent.
3958 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3959 // Get the array position of the default user agent name.
3960 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3962 // Set the user agent according to the system default.
3963 switch (defaultUserAgentArrayPosition) {
3964 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3965 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3966 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3969 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3970 // Set the user agent to `""`, which uses the default value.
3971 mainWebView.getSettings().setUserAgentString("");
3974 case SETTINGS_CUSTOM_USER_AGENT:
3975 // Set the custom user agent.
3976 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3980 // Get the user agent string from the user agent data array
3981 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3983 } else { // Set the user agent according to the stored name.
3984 // Get the array position of the user agent name.
3985 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3987 switch (userAgentArrayPosition) {
3988 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3989 mainWebView.getSettings().setUserAgentString(userAgentName);
3992 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3993 // Set the user agent to `""`, which uses the default value.
3994 mainWebView.getSettings().setUserAgentString("");
3998 // Get the user agent string from the user agent data array.
3999 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4003 // Set swipe to refresh.
4004 switch (swipeToRefreshInt) {
4005 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
4006 // Set swipe to refresh according to the default.
4007 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4010 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
4011 // Enable swipe to refresh.
4012 swipeRefreshLayout.setEnabled(true);
4015 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
4016 // Disable swipe to refresh.
4017 swipeRefreshLayout.setEnabled(false);
4020 // Store the applied user agent string, which is used in the View Source activity.
4021 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4024 // 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.
4026 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4028 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4030 } else { // The new URL does not have custom domain settings. Load the defaults.
4031 // Store the values from `sharedPreferences` in variables.
4032 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
4033 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
4034 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
4035 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
4036 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false); // Form data can be removed once the minimum API >= 26.
4037 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
4038 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
4039 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
4040 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
4041 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
4042 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
4044 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4046 javaScriptEnabled = true;
4049 // Apply the default settings.
4050 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4051 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4052 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4053 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4054 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4056 // Apply the form data setting if the API < 26.
4057 if (Build.VERSION.SDK_INT < 26) {
4058 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4061 // Reset the pinned SSL certificate information.
4062 domainSettingsDatabaseId = -1;
4063 pinnedDomainSslCertificate = false;
4064 pinnedDomainSslIssuedToCNameString = "";
4065 pinnedDomainSslIssuedToONameString = "";
4066 pinnedDomainSslIssuedToUNameString = "";
4067 pinnedDomainSslIssuedByCNameString = "";
4068 pinnedDomainSslIssuedByONameString = "";
4069 pinnedDomainSslIssuedByUNameString = "";
4070 pinnedDomainSslStartDate = null;
4071 pinnedDomainSslEndDate = null;
4073 // Set third-party cookies status if API >= 21.
4074 if (Build.VERSION.SDK_INT >= 21) {
4075 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4078 // 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.
4079 // <https://redmine.stoutner.com/issues/160>
4080 if (!urlIsLoading) {
4081 // Get the array position of the user agent name.
4082 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4084 // Set the user agent.
4085 switch (userAgentArrayPosition) {
4086 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4087 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4088 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4091 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4092 // Set the user agent to `""`, which uses the default value.
4093 mainWebView.getSettings().setUserAgentString("");
4096 case SETTINGS_CUSTOM_USER_AGENT:
4097 // Set the custom user agent.
4098 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4102 // Get the user agent string from the user agent data array
4103 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4106 // Store the applied user agent string, which is used in the View Source activity.
4107 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4110 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4111 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4114 // Close `domainsDatabaseHelper`.
4115 domainsDatabaseHelper.close();
4117 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
4118 onTheFlyDisplayImagesSet = false;
4119 setDisplayWebpageImages();
4121 // Update the privacy icons, but only if `mainMenu` has already been populated.
4122 if (mainMenu != null) {
4123 updatePrivacyIcons(true);
4127 // Reload the website if returning from the Domains activity.
4128 if (reloadWebsite) {
4129 mainWebView.reload();
4133 private void setDisplayWebpageImages() {
4134 if (!onTheFlyDisplayImagesSet) {
4135 if (domainSettingsApplied) { // Custom domain settings are applied.
4136 switch (displayWebpageImagesInt) {
4137 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4138 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4141 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4142 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4145 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4146 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4149 } else { // Default settings are applied.
4150 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4155 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4156 // Get handles for the menu items.
4157 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4158 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4159 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4160 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4162 // Update the privacy icon.
4163 if (javaScriptEnabled) { // JavaScript is enabled.
4164 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4165 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4166 privacyMenuItem.setIcon(R.drawable.warning);
4167 } else { // All the dangerous features are disabled.
4168 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4171 // Update the first-party cookies icon.
4172 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4173 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4174 } else { // First-party cookies are disabled.
4176 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4178 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4182 // Update the DOM storage icon.
4183 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4184 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4185 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4187 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4189 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4191 } else { // JavaScript is disabled, so DOM storage is ghosted.
4193 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4195 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4199 // Update the refresh icon.
4201 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4203 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4206 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4207 if (runInvalidateOptionsMenu) {
4208 invalidateOptionsMenu();
4212 private void highlightUrlText() {
4213 String urlString = urlTextBox.getText().toString();
4215 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4216 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4217 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4218 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4221 // Get the index of the `/` immediately after the domain name.
4222 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4224 // De-emphasize the text after the domain name.
4225 if (endOfDomainName > 0) {
4226 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4230 private void loadBookmarksFolder() {
4231 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4232 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4234 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4235 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4237 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4238 // Inflate the individual item layout. `false` does not attach it to the root.
4239 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4243 public void bindView(View view, Context context, Cursor cursor) {
4244 // Get handles for the views.
4245 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4246 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4248 // Get the favorite icon byte array from the cursor.
4249 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4251 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4252 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4254 // Display the bitmap in `bookmarkFavoriteIcon`.
4255 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4257 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4258 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4259 bookmarkNameTextView.setText(bookmarkNameString);
4261 // Make the font bold for folders.
4262 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4263 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4264 } else { // Reset the font to default for normal bookmarks.
4265 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4270 // Populate the `ListView` with the adapter.
4271 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4273 // Set the bookmarks drawer title.
4274 if (currentBookmarksFolder.isEmpty()) {
4275 bookmarksTitleTextView.setText(R.string.bookmarks);
4277 bookmarksTitleTextView.setText(currentBookmarksFolder);