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 // Reset the Refresh title.
1549 refreshMenuItem.setTitle(R.string.refresh);
1551 // If the icon is displayed in the AppBar, reset it according to the theme.
1552 if (displayAdditionalAppBarIcons) {
1554 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1556 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1560 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1561 urlIsLoading = false;
1563 // Clear the cache and history if Incognito Mode is enabled.
1564 if (incognitoModeEnabled) {
1565 // Clear the cache. `true` includes disk files.
1566 mainWebView.clearCache(true);
1568 // Clear the back/forward history.
1569 mainWebView.clearHistory();
1571 // Manually delete cache folders.
1573 // Delete the main cache directory.
1574 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1576 // Delete the secondary `Service Worker` cache directory.
1577 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1578 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1579 } catch (IOException e) {
1580 // Do nothing if an error is thrown.
1584 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1585 if (!waitingForOrbot) {
1586 // Check to see if `WebView` has set `url` to be `about:blank`.
1587 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1588 // Set `formattedUrlString` to `""`.
1589 formattedUrlString = "";
1591 urlTextBox.setText(formattedUrlString);
1593 // Request focus for `urlTextBox`.
1594 urlTextBox.requestFocus();
1596 // Display the keyboard.
1597 inputMethodManager.showSoftInput(urlTextBox, 0);
1599 // Apply the domain settings. This clears any settings from the previous domain.
1600 applyDomainSettings(formattedUrlString, true, false);
1601 } else { // `WebView` has loaded a webpage.
1602 // Set `formattedUrlString`.
1603 formattedUrlString = url;
1605 // Only update `urlTextBox` if the user is not typing in it.
1606 if (!urlTextBox.hasFocus()) {
1607 // Display the formatted URL text.
1608 urlTextBox.setText(formattedUrlString);
1610 // Apply text highlighting to `urlTextBox`.
1615 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1616 sslCertificate = mainWebView.getCertificate();
1618 // 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.
1619 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1620 // Initialize the current SSL certificate variables.
1621 String currentWebsiteIssuedToCName = "";
1622 String currentWebsiteIssuedToOName = "";
1623 String currentWebsiteIssuedToUName = "";
1624 String currentWebsiteIssuedByCName = "";
1625 String currentWebsiteIssuedByOName = "";
1626 String currentWebsiteIssuedByUName = "";
1627 Date currentWebsiteSslStartDate = null;
1628 Date currentWebsiteSslEndDate = null;
1631 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1632 if (sslCertificate != null) {
1633 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1634 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1635 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1636 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1637 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1638 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1639 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1640 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1643 // 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`.
1644 String currentWebsiteSslStartDateString = "";
1645 String currentWebsiteSslEndDateString = "";
1646 String pinnedDomainSslStartDateString = "";
1647 String pinnedDomainSslEndDateString = "";
1649 // Convert the `Dates` to `Strings` if they are not `null`.
1650 if (currentWebsiteSslStartDate != null) {
1651 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1654 if (currentWebsiteSslEndDate != null) {
1655 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1658 if (pinnedDomainSslStartDate != null) {
1659 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1662 if (pinnedDomainSslEndDate != null) {
1663 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1666 // Check to see if the pinned SSL certificate matches the current website certificate.
1667 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1668 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1669 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1670 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1671 // The pinned SSL certificate doesn't match the current domain certificate.
1672 //Display the pinned SSL certificate mismatch `AlertDialog`.
1673 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1674 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1680 // Handle SSL Certificate errors.
1682 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1683 // Get the current website SSL certificate.
1684 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1686 // Extract the individual pieces of information from the current website SSL certificate.
1687 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1688 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1689 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1690 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1691 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1692 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1693 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1694 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1696 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1697 if (pinnedDomainSslCertificate &&
1698 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1699 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1700 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1701 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1702 // An SSL certificate is pinned and matches the current domain certificate.
1703 // Proceed to the website without displaying an error.
1705 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1706 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1707 sslErrorHandler = handler;
1709 // Display the SSL error `AlertDialog`.
1710 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1711 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1716 // Load the website if not waiting for Orbot to connect.
1717 if (!waitingForOrbot) {
1718 loadUrl(formattedUrlString);
1723 protected void onNewIntent(Intent intent) {
1724 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1727 // Check to see if the intent contains a new URL.
1728 if (intent.getData() != null) {
1729 // Get the intent data.
1730 final Uri intentUriData = intent.getData();
1732 // Load the website.
1733 loadUrl(intentUriData.toString());
1735 // Close the navigation drawer if it is open.
1736 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1737 drawerLayout.closeDrawer(GravityCompat.START);
1740 // Close the bookmarks drawer if it is open.
1741 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1742 drawerLayout.closeDrawer(GravityCompat.END);
1745 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1746 mainWebView.requestFocus();
1751 public void onRestart() {
1752 // Run the default commands.
1755 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1756 if (proxyThroughOrbot) {
1757 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1758 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1760 // Send the intent to the Orbot package.
1761 orbotIntent.setPackage("org.torproject.android");
1764 sendBroadcast(orbotIntent);
1767 // Apply the app settings if returning from the Settings activity..
1768 if (reapplyAppSettingsOnRestart) {
1769 // Apply the app settings.
1772 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1773 if (reloadOnRestart) {
1774 // Reload `mainWebView`.
1775 mainWebView.reload();
1777 // Reset `reloadOnRestartBoolean`.
1778 reloadOnRestart = false;
1781 // Reset the return from settings flag.
1782 reapplyAppSettingsOnRestart = false;
1785 // Apply the domain settings if returning from the Domains activity.
1786 if (reapplyDomainSettingsOnRestart) {
1787 // Reapply the domain settings.
1788 applyDomainSettings(formattedUrlString, false, true);
1790 // Reset `reapplyDomainSettingsOnRestart`.
1791 reapplyDomainSettingsOnRestart = false;
1794 // Load the URL on restart to apply changes to night mode.
1795 if (loadUrlOnRestart) {
1796 // Load the current `formattedUrlString`.
1797 loadUrl(formattedUrlString);
1799 // Reset `loadUrlOnRestart.
1800 loadUrlOnRestart = false;
1803 // Update the bookmarks drawer if returning from the Bookmarks activity.
1804 if (restartFromBookmarksActivity) {
1805 // Close the bookmarks drawer.
1806 drawerLayout.closeDrawer(GravityCompat.END);
1808 // Reload the bookmarks drawer.
1809 loadBookmarksFolder();
1811 // Reset `restartFromBookmarksActivity`.
1812 restartFromBookmarksActivity = false;
1815 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1816 updatePrivacyIcons(true);
1819 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1821 public void onResume() {
1822 // Run the default commands.
1825 // Resume JavaScript (if enabled).
1826 mainWebView.resumeTimers();
1828 // Resume `mainWebView`.
1829 mainWebView.onResume();
1831 // Resume the adView for the free flavor.
1832 if (BuildConfig.FLAVOR.contentEquals("free")) {
1834 AdHelper.resumeAd(findViewById(R.id.adview));
1837 // Display a message to the user if waiting for Orbot.
1838 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1839 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1840 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1843 if (displayingFullScreenVideo) {
1844 // Remove the translucent overlays.
1845 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1847 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1848 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1850 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1851 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1852 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1854 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1859 public void onPause() {
1860 // Run the default commands.
1863 // Pause `mainWebView`.
1864 mainWebView.onPause();
1866 // Stop all JavaScript.
1867 mainWebView.pauseTimers();
1869 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1870 if (BuildConfig.FLAVOR.contentEquals("free")) {
1872 AdHelper.pauseAd(findViewById(R.id.adview));
1877 public void onDestroy() {
1878 // Unregister the Orbot status broadcast receiver.
1879 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1881 // Run the default commands.
1886 public boolean onCreateOptionsMenu(Menu menu) {
1887 // Inflate the menu; this adds items to the action bar if it is present.
1888 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1890 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1893 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1894 updatePrivacyIcons(false);
1896 // Get handles for the menu items.
1897 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1898 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1899 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1900 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1901 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1902 refreshMenuItem = menu.findItem(R.id.refresh);
1903 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1905 // Only display third-party cookies if API >= 21
1906 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1908 // Only display the form data menu items if the API < 26.
1909 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1910 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1912 // Only show Ad Consent if this is the free flavor.
1913 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1915 // Get the shared preference values.
1916 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1918 // Get the status of the additional AppBar icons.
1919 displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
1921 // 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.
1922 if (displayAdditionalAppBarIcons) {
1923 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1924 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1925 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1926 } else { //Do not display the additional icons.
1927 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1928 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1929 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1932 // Replace Refresh with Stop if a URL is already loading.
1935 refreshMenuItem.setTitle(R.string.stop);
1937 // If the icon is displayed in the AppBar, set it according to the theme.
1938 if (displayAdditionalAppBarIcons) {
1940 refreshMenuItem.setIcon(R.drawable.close_dark);
1942 refreshMenuItem.setIcon(R.drawable.close_light);
1951 public boolean onPrepareOptionsMenu(Menu menu) {
1952 // Get handles for the menu items.
1953 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1954 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1955 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1956 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1957 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1958 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1959 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1960 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1961 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1962 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1963 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1964 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1965 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1966 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1967 MenuItem blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1968 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1969 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1970 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1972 // Set the text for the domain menu item.
1973 if (domainSettingsApplied) {
1974 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1976 addOrEditDomain.setTitle(R.string.add_domain_settings);
1979 // Set the status of the menu item checkboxes.
1980 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1981 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1982 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1983 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
1984 easyListMenuItem.setChecked(easyListEnabled);
1985 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1986 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1987 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1988 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
1989 blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1990 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1991 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1993 // Enable third-party cookies if first-party cookies are enabled.
1994 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1996 // Enable DOM Storage if JavaScript is enabled.
1997 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1999 // Enable Clear Cookies if there are any.
2000 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2002 // Get a count of the number of files in the Local Storage directory.
2003 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2004 int localStorageDirectoryNumberOfFiles = 0;
2005 if (localStorageDirectory.exists()) {
2006 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2009 // Get a count of the number of files in the IndexedDB directory.
2010 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2011 int indexedDBDirectoryNumberOfFiles = 0;
2012 if (indexedDBDirectory.exists()) {
2013 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2016 // Enable Clear DOM Storage if there is any.
2017 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2019 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
2020 if (Build.VERSION.SDK_INT < 26) {
2021 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2022 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2024 // Disable clear form data because it is not supported on current version of Android.
2025 clearFormDataMenuItem.setEnabled(false);
2028 // Enable Clear Data if any of the submenu items are enabled.
2029 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2031 // Update the display names for the blocklists with the number of blocked requests.
2032 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2033 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2034 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2035 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2036 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2037 blockAllThirdParyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2039 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2040 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2042 // Initialize font size variables.
2043 int fontSize = mainWebView.getSettings().getTextZoom();
2044 String fontSizeTitle;
2045 MenuItem selectedFontSizeMenuItem;
2047 // Prepare the font size title and current size menu item.
2050 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2051 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2055 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2056 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2060 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2061 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2065 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2066 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2070 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2071 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2075 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2076 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2080 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2081 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2085 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2086 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2090 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2091 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2095 // Set the font size title and select the current size menu item.
2096 fontSizeMenuItem.setTitle(fontSizeTitle);
2097 selectedFontSizeMenuItem.setChecked(true);
2099 // Run all the other default commands.
2100 super.onPrepareOptionsMenu(menu);
2102 // Display the menu.
2107 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2108 @SuppressLint("SetJavaScriptEnabled")
2109 // removeAllCookies is deprecated, but it is required for API < 21.
2110 @SuppressWarnings("deprecation")
2111 public boolean onOptionsItemSelected(MenuItem menuItem) {
2112 // Get the selected menu item ID.
2113 int menuItemId = menuItem.getItemId();
2115 // Set the commands that relate to the menu entries.
2116 switch (menuItemId) {
2117 case R.id.toggle_javascript:
2118 // Switch the status of javaScriptEnabled.
2119 javaScriptEnabled = !javaScriptEnabled;
2121 // Apply the new JavaScript status.
2122 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2124 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2125 updatePrivacyIcons(true);
2127 // Display a `Snackbar`.
2128 if (javaScriptEnabled) { // JavaScrip is enabled.
2129 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2130 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2131 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2132 } else { // Privacy mode.
2133 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2136 // Reload the WebView.
2137 mainWebView.reload();
2140 case R.id.add_or_edit_domain:
2141 if (domainSettingsApplied) { // Edit the current domain settings.
2142 // Reapply the domain settings on returning to `MainWebViewActivity`.
2143 reapplyDomainSettingsOnRestart = true;
2144 currentDomainName = "";
2146 // Create an intent to launch the domains activity.
2147 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2149 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2150 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2151 domainsIntent.putExtra("closeOnBack", true);
2154 startActivity(domainsIntent);
2155 } else { // Add a new domain.
2156 // Apply the new domain settings on returning to `MainWebViewActivity`.
2157 reapplyDomainSettingsOnRestart = true;
2158 currentDomainName = "";
2160 // Get the current domain
2161 Uri currentUri = Uri.parse(formattedUrlString);
2162 String currentDomain = currentUri.getHost();
2164 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2165 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2167 // Create the domain and store the database ID.
2168 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2170 // Create an intent to launch the domains activity.
2171 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2173 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2174 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2175 domainsIntent.putExtra("closeOnBack", true);
2178 startActivity(domainsIntent);
2182 case R.id.toggle_first_party_cookies:
2183 // Switch the status of firstPartyCookiesEnabled.
2184 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2186 // Update the menu checkbox.
2187 menuItem.setChecked(firstPartyCookiesEnabled);
2189 // Apply the new cookie status.
2190 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2192 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2193 updatePrivacyIcons(true);
2195 // Display a `Snackbar`.
2196 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2197 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2198 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2199 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2200 } else { // Privacy mode.
2201 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2204 // Reload the WebView.
2205 mainWebView.reload();
2208 case R.id.toggle_third_party_cookies:
2209 if (Build.VERSION.SDK_INT >= 21) {
2210 // Switch the status of thirdPartyCookiesEnabled.
2211 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2213 // Update the menu checkbox.
2214 menuItem.setChecked(thirdPartyCookiesEnabled);
2216 // Apply the new cookie status.
2217 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2219 // Display a `Snackbar`.
2220 if (thirdPartyCookiesEnabled) {
2221 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2223 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2226 // Reload the WebView.
2227 mainWebView.reload();
2228 } // Else do nothing because SDK < 21.
2231 case R.id.toggle_dom_storage:
2232 // Switch the status of domStorageEnabled.
2233 domStorageEnabled = !domStorageEnabled;
2235 // Update the menu checkbox.
2236 menuItem.setChecked(domStorageEnabled);
2238 // Apply the new DOM Storage status.
2239 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2241 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2242 updatePrivacyIcons(true);
2244 // Display a `Snackbar`.
2245 if (domStorageEnabled) {
2246 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2248 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2251 // Reload the WebView.
2252 mainWebView.reload();
2255 // Form data can be removed once the minimum API >= 26.
2256 case R.id.toggle_save_form_data:
2257 // Switch the status of saveFormDataEnabled.
2258 saveFormDataEnabled = !saveFormDataEnabled;
2260 // Update the menu checkbox.
2261 menuItem.setChecked(saveFormDataEnabled);
2263 // Apply the new form data status.
2264 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2266 // Display a `Snackbar`.
2267 if (saveFormDataEnabled) {
2268 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2270 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2273 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2274 updatePrivacyIcons(true);
2276 // Reload the WebView.
2277 mainWebView.reload();
2280 case R.id.clear_cookies:
2281 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2282 .setAction(R.string.undo, v -> {
2283 // Do nothing because everything will be handled by `onDismissed()` below.
2285 .addCallback(new Snackbar.Callback() {
2287 public void onDismissed(Snackbar snackbar, int event) {
2289 // The user pushed the `Undo` button.
2290 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2294 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2296 // `cookieManager.removeAllCookie()` varies by SDK.
2297 if (Build.VERSION.SDK_INT < 21) {
2298 cookieManager.removeAllCookie();
2300 // `null` indicates no callback.
2301 cookieManager.removeAllCookies(null);
2309 case R.id.clear_dom_storage:
2310 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2311 .setAction(R.string.undo, v -> {
2312 // Do nothing because everything will be handled by `onDismissed()` below.
2314 .addCallback(new Snackbar.Callback() {
2316 public void onDismissed(Snackbar snackbar, int event) {
2318 // The user pushed the `Undo` button.
2319 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2323 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2325 // Delete the DOM Storage.
2326 WebStorage webStorage = WebStorage.getInstance();
2327 webStorage.deleteAllData();
2329 // Manually delete the DOM storage files and directories.
2331 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2332 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2334 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2335 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2336 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2337 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2338 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2339 } catch (IOException e) {
2340 // Do nothing if an error is thrown.
2348 // Form data can be remove once the minimum API >= 26.
2349 case R.id.clear_form_data:
2350 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2351 .setAction(R.string.undo, v -> {
2352 // Do nothing because everything will be handled by `onDismissed()` below.
2354 .addCallback(new Snackbar.Callback() {
2356 public void onDismissed(Snackbar snackbar, int event) {
2358 // The user pushed the `Undo` button.
2359 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2363 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2365 // Delete the form data.
2366 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2367 mainWebViewDatabase.clearFormData();
2374 case R.id.font_size_twenty_five_percent:
2375 mainWebView.getSettings().setTextZoom(25);
2378 case R.id.font_size_fifty_percent:
2379 mainWebView.getSettings().setTextZoom(50);
2382 case R.id.font_size_seventy_five_percent:
2383 mainWebView.getSettings().setTextZoom(75);
2386 case R.id.font_size_one_hundred_percent:
2387 mainWebView.getSettings().setTextZoom(100);
2390 case R.id.font_size_one_hundred_twenty_five_percent:
2391 mainWebView.getSettings().setTextZoom(125);
2394 case R.id.font_size_one_hundred_fifty_percent:
2395 mainWebView.getSettings().setTextZoom(150);
2398 case R.id.font_size_one_hundred_seventy_five_percent:
2399 mainWebView.getSettings().setTextZoom(175);
2402 case R.id.font_size_two_hundred_percent:
2403 mainWebView.getSettings().setTextZoom(200);
2406 case R.id.swipe_to_refresh:
2407 // Toggle swipe to refresh.
2408 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2411 case R.id.display_images:
2412 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2413 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2414 mainWebView.reload();
2415 } else { // Images are not currently loaded automatically.
2416 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2419 // Set `onTheFlyDisplayImagesSet`.
2420 onTheFlyDisplayImagesSet = true;
2423 case R.id.view_source:
2424 // Launch the View Source activity.
2425 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2426 startActivity(viewSourceIntent);
2430 // Toggle the EasyList status.
2431 easyListEnabled = !easyListEnabled;
2433 // Update the menu checkbox.
2434 menuItem.setChecked(easyListEnabled);
2436 // Reload the main WebView.
2437 mainWebView.reload();
2440 case R.id.easyprivacy:
2441 // Toggle the EasyPrivacy status.
2442 easyPrivacyEnabled = !easyPrivacyEnabled;
2444 // Update the menu checkbox.
2445 menuItem.setChecked(easyPrivacyEnabled);
2447 // Reload the main WebView.
2448 mainWebView.reload();
2451 case R.id.fanboys_annoyance_list:
2452 // Toggle Fanboy's Annoyance List status.
2453 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2455 // Update the menu checkbox.
2456 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2458 // Update the staus of Fanboy's Social Blocking List.
2459 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2460 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2462 // Reload the main WebView.
2463 mainWebView.reload();
2466 case R.id.fanboys_social_blocking_list:
2467 // Toggle Fanboy's Social Blocking List status.
2468 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2470 // Update the menu checkbox.
2471 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2473 // Reload the main WebView.
2474 mainWebView.reload();
2477 case R.id.ultraprivacy:
2478 // Toggle the UltraPrivacy status.
2479 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2481 // Update the menu checkbox.
2482 menuItem.setChecked(ultraPrivacyEnabled);
2484 // Reload the main WebView.
2485 mainWebView.reload();
2488 case R.id.block_all_third_party_requests:
2489 //Toggle the third-party requests blocker status.
2490 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2492 // Update the menu checkbox.
2493 menuItem.setChecked(blockAllThirdPartyRequests);
2495 // Reload the main WebView.
2496 mainWebView.reload();
2500 // Setup the share string.
2501 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2503 // Create the share intent.
2504 Intent shareIntent = new Intent();
2505 shareIntent.setAction(Intent.ACTION_SEND);
2506 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2507 shareIntent.setType("text/plain");
2510 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2513 case R.id.find_on_page:
2514 // Hide the URL app bar.
2515 supportAppBar.setVisibility(View.GONE);
2517 // Show the Find on Page `RelativeLayout`.
2518 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2520 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2521 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2522 findOnPageEditText.postDelayed(() -> {
2523 // Set the focus on `findOnPageEditText`.
2524 findOnPageEditText.requestFocus();
2526 // Display the keyboard. `0` sets no input flags.
2527 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2532 // Get a `PrintManager` instance.
2533 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2535 // Convert `mainWebView` to `printDocumentAdapter`.
2536 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2538 // Remove the lint error below that `printManager` might be `null`.
2539 assert printManager != null;
2541 // Print the document. The print attributes are `null`.
2542 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2545 case R.id.add_to_homescreen:
2546 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2547 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2548 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2550 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2554 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2555 // Reload the WebView.
2556 mainWebView.reload();
2557 } else { // The stop button was pushed.
2558 // Stop the loading of the WebView.
2559 mainWebView.stopLoading();
2563 case R.id.ad_consent:
2564 // Display the ad consent dialog.
2565 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2566 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2570 // Don't consume the event.
2571 return super.onOptionsItemSelected(menuItem);
2575 // removeAllCookies is deprecated, but it is required for API < 21.
2576 @SuppressWarnings("deprecation")
2578 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2579 int menuItemId = menuItem.getItemId();
2581 switch (menuItemId) {
2587 if (mainWebView.canGoBack()) {
2588 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2589 formattedUrlString = "";
2591 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2592 navigatingHistory = true;
2594 // Load the previous website in the history.
2595 mainWebView.goBack();
2600 if (mainWebView.canGoForward()) {
2601 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2602 formattedUrlString = "";
2604 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2605 navigatingHistory = true;
2607 // Load the next website in the history.
2608 mainWebView.goForward();
2613 // Get the `WebBackForwardList`.
2614 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2616 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2617 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2618 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2622 // Launch the requests activity.
2623 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2624 startActivity(requestsIntent);
2627 case R.id.downloads:
2628 // Launch the system Download Manager.
2629 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2631 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2632 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2634 startActivity(downloadManagerIntent);
2638 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2639 reapplyDomainSettingsOnRestart = true;
2640 currentDomainName = "";
2642 // Launch the domains activity.
2643 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2644 startActivity(domainsIntent);
2648 // Set the flag to reapply app settings on restart when returning from Settings.
2649 reapplyAppSettingsOnRestart = true;
2651 // Set the flag to reapply the domain settings on restart when returning from Settings.
2652 reapplyDomainSettingsOnRestart = true;
2653 currentDomainName = "";
2655 // Launch the settings activity.
2656 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2657 startActivity(settingsIntent);
2661 // Launch `GuideActivity`.
2662 Intent guideIntent = new Intent(this, GuideActivity.class);
2663 startActivity(guideIntent);
2667 // Launch `AboutActivity`.
2668 Intent aboutIntent = new Intent(this, AboutActivity.class);
2669 startActivity(aboutIntent);
2672 case R.id.clearAndExit:
2673 // Get a handle for `sharedPreferences`. `this` references the current context.
2674 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2676 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2679 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2680 // The command to remove cookies changed slightly in API 21.
2681 if (Build.VERSION.SDK_INT >= 21) {
2682 cookieManager.removeAllCookies(null);
2684 cookieManager.removeAllCookie();
2687 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2689 // We have to use two commands because `Runtime.exec()` does not like `*`.
2690 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2691 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2692 } catch (IOException e) {
2693 // Do nothing if an error is thrown.
2697 // Clear DOM storage.
2698 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2699 // Ask `WebStorage` to clear the DOM storage.
2700 WebStorage webStorage = WebStorage.getInstance();
2701 webStorage.deleteAllData();
2703 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2705 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2706 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2708 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2709 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2710 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2711 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2712 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2713 } catch (IOException e) {
2714 // Do nothing if an error is thrown.
2718 // Clear form data if the API < 26.
2719 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2720 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2721 webViewDatabase.clearFormData();
2723 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2725 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2726 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2727 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2728 } catch (IOException e) {
2729 // Do nothing if an error is thrown.
2734 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2735 // `true` includes disk files.
2736 mainWebView.clearCache(true);
2738 // Manually delete the cache directories.
2740 // Delete the main cache directory.
2741 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2743 // Delete the secondary `Service Worker` cache directory.
2744 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2745 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2746 } catch (IOException e) {
2747 // Do nothing if an error is thrown.
2751 // Clear SSL certificate preferences.
2752 mainWebView.clearSslPreferences();
2754 // Clear the back/forward history.
2755 mainWebView.clearHistory();
2757 // Clear `formattedUrlString`.
2758 formattedUrlString = null;
2760 // Clear `customHeaders`.
2761 customHeaders.clear();
2763 // Detach all views from `mainWebViewRelativeLayout`.
2764 mainWebViewRelativeLayout.removeAllViews();
2766 // Destroy the internal state of `mainWebView`.
2767 mainWebView.destroy();
2769 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2770 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2771 if (clearEverything) {
2773 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2774 } catch (IOException e) {
2775 // Do nothing if an error is thrown.
2779 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2780 if (Build.VERSION.SDK_INT >= 21) {
2781 finishAndRemoveTask();
2786 // Remove the terminated program from RAM. The status code is `0`.
2791 // Close the navigation drawer.
2792 drawerLayout.closeDrawer(GravityCompat.START);
2797 public void onPostCreate(Bundle savedInstanceState) {
2798 super.onPostCreate(savedInstanceState);
2800 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2801 drawerToggle.syncState();
2805 public void onConfigurationChanged(Configuration newConfig) {
2806 super.onConfigurationChanged(newConfig);
2808 // Reload the ad for the free flavor if we not in full screen mode.
2809 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2810 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2811 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2814 // `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:
2815 // https://code.google.com/p/android/issues/detail?id=20493#c8
2816 // ActivityCompat.invalidateOptionsMenu(this);
2820 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2821 // Store the `HitTestResult`.
2822 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2825 final String imageUrl;
2826 final String linkUrl;
2828 // Get a handle for the `ClipboardManager`.
2829 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2831 // Remove the lint errors below that `clipboardManager` might be `null`.
2832 assert clipboardManager != null;
2834 switch (hitTestResult.getType()) {
2835 // `SRC_ANCHOR_TYPE` is a link.
2836 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2837 // Get the target URL.
2838 linkUrl = hitTestResult.getExtra();
2840 // Set the target URL as the title of the `ContextMenu`.
2841 menu.setHeaderTitle(linkUrl);
2843 // Add a Load URL entry.
2844 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2849 // Add a Copy URL entry.
2850 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2851 // Save the link URL in a `ClipData`.
2852 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2854 // Set the `ClipData` as the clipboard's primary clip.
2855 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2859 // Add a Download URL entry.
2860 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2861 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2862 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2863 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2865 // Store the variables for future use by `onRequestPermissionsResult()`.
2866 downloadUrl = linkUrl;
2867 downloadContentDisposition = "none";
2868 downloadContentLength = -1;
2870 // Show a dialog if the user has previously denied the permission.
2871 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2872 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2873 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2875 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2876 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2877 } else { // Show the permission request directly.
2878 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2879 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2881 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2882 // Get a handle for the download file alert dialog.
2883 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2885 // Show the download file alert dialog.
2886 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2891 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2892 menu.add(R.string.cancel);
2895 case WebView.HitTestResult.EMAIL_TYPE:
2896 // Get the target URL.
2897 linkUrl = hitTestResult.getExtra();
2899 // Set the target URL as the title of the `ContextMenu`.
2900 menu.setHeaderTitle(linkUrl);
2902 // Add a `Write Email` entry.
2903 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2904 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2905 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2907 // Parse the url and set it as the data for the `Intent`.
2908 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2910 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2911 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2914 startActivity(emailIntent);
2918 // Add a `Copy Email Address` entry.
2919 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2920 // Save the email address in a `ClipData`.
2921 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2923 // Set the `ClipData` as the clipboard's primary clip.
2924 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2928 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2929 menu.add(R.string.cancel);
2932 // `IMAGE_TYPE` is an image.
2933 case WebView.HitTestResult.IMAGE_TYPE:
2934 // Get the image URL.
2935 imageUrl = hitTestResult.getExtra();
2937 // Set the image URL as the title of the `ContextMenu`.
2938 menu.setHeaderTitle(imageUrl);
2940 // Add a `View Image` entry.
2941 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2946 // Add a `Download Image` entry.
2947 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2948 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2949 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2950 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2952 // Store the image URL for use by `onRequestPermissionResult()`.
2953 downloadImageUrl = imageUrl;
2955 // Show a dialog if the user has previously denied the permission.
2956 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2957 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2958 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2960 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2961 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2962 } else { // Show the permission request directly.
2963 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2964 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2966 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2967 // Get a handle for the download image alert dialog.
2968 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2970 // Show the download image alert dialog.
2971 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2976 // Add a `Copy URL` entry.
2977 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2978 // Save the image URL in a `ClipData`.
2979 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2981 // Set the `ClipData` as the clipboard's primary clip.
2982 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2986 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2987 menu.add(R.string.cancel);
2991 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2992 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2993 // Get the image URL.
2994 imageUrl = hitTestResult.getExtra();
2996 // Set the image URL as the title of the `ContextMenu`.
2997 menu.setHeaderTitle(imageUrl);
2999 // Add a `View Image` entry.
3000 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3005 // Add a `Download Image` entry.
3006 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3007 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
3008 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
3009 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
3011 // Store the image URL for use by `onRequestPermissionResult()`.
3012 downloadImageUrl = imageUrl;
3014 // Show a dialog if the user has previously denied the permission.
3015 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3016 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3017 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3019 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3020 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3021 } else { // Show the permission request directly.
3022 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3023 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3025 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
3026 // Get a handle for the download image alert dialog.
3027 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3029 // Show the download image alert dialog.
3030 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3035 // Add a `Copy URL` entry.
3036 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3037 // Save the image URL in a `ClipData`.
3038 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3040 // Set the `ClipData` as the clipboard's primary clip.
3041 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3045 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3046 menu.add(R.string.cancel);
3052 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3053 // Get the `EditTexts` from the `dialogFragment`.
3054 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3055 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3057 // Extract the strings from the `EditTexts`.
3058 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3059 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3061 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3062 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3063 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3064 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3066 // Display the new bookmark below the current items in the (0 indexed) list.
3067 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3069 // Create the bookmark.
3070 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3072 // Update `bookmarksCursor` with the current contents of this folder.
3073 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3075 // Update the `ListView`.
3076 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3078 // Scroll to the new bookmark.
3079 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3083 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3084 // Get handles for the views in `dialogFragment`.
3085 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3086 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3087 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3089 // Get new folder name string.
3090 String folderNameString = createFolderNameEditText.getText().toString();
3092 // Get the new folder icon `Bitmap`.
3093 Bitmap folderIconBitmap;
3094 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3095 // Get the default folder icon and convert it to a `Bitmap`.
3096 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3097 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3098 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3099 } else { // Use the `WebView` favorite icon.
3100 folderIconBitmap = favoriteIconBitmap;
3103 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3104 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3105 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3106 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3108 // Move all the bookmarks down one in the display order.
3109 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3110 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3111 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3114 // Create the folder, which will be placed at the top of the `ListView`.
3115 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3117 // Update `bookmarksCursor` with the current contents of this folder.
3118 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3120 // Update the `ListView`.
3121 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3123 // Scroll to the new folder.
3124 bookmarksListView.setSelection(0);
3128 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3129 // Get the shortcut name.
3130 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3131 String shortcutNameString = shortcutNameEditText.getText().toString();
3133 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3134 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3136 // Setup the shortcut intent.
3137 Intent shortcutIntent = new Intent();
3138 shortcutIntent.setAction(Intent.ACTION_VIEW);
3139 shortcutIntent.setData(Uri.parse(formattedUrlString));
3141 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3142 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3144 // Add the required fields to the shortcut info builder.
3145 shortcutInfoBuilder.setIcon(favoriteIcon);
3146 shortcutInfoBuilder.setIntent(shortcutIntent);
3147 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3149 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3150 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3154 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3155 switch (downloadType) {
3156 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3157 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3158 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3161 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3162 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3163 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3169 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
3170 switch (requestCode) {
3171 case DOWNLOAD_FILE_REQUEST_CODE:
3172 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3173 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3175 // On API 23, displaying the fragment must be delayed or the app will crash.
3176 if (Build.VERSION.SDK_INT == 23) {
3177 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3179 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3182 // Reset the download variables.
3184 downloadContentDisposition = "";
3185 downloadContentLength = 0;
3188 case DOWNLOAD_IMAGE_REQUEST_CODE:
3189 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3190 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3192 // On API 23, displaying the fragment must be delayed or the app will crash.
3193 if (Build.VERSION.SDK_INT == 23) {
3194 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3196 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3199 // Reset the image URL variable.
3200 downloadImageUrl = "";
3206 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3207 // Download the image if it has an HTTP or HTTPS URI.
3208 if (imageUrl.startsWith("http")) {
3209 // Get a handle for the system `DOWNLOAD_SERVICE`.
3210 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3212 // Parse `imageUrl`.
3213 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3215 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3216 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3217 if (firstPartyCookiesEnabled) {
3218 // Get the cookies for `imageUrl`.
3219 String cookies = cookieManager.getCookie(imageUrl);
3221 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3222 downloadRequest.addRequestHeader("Cookie", cookies);
3225 // Get the file name from the dialog fragment.
3226 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3227 String imageName = downloadImageNameEditText.getText().toString();
3229 // Specify the download location.
3230 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3231 // Download to the public download directory.
3232 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3233 } else { // External write permission denied.
3234 // Download to the app's external download directory.
3235 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3238 // Allow `MediaScanner` to index the download if it is a media file.
3239 downloadRequest.allowScanningByMediaScanner();
3241 // Add the URL as the description for the download.
3242 downloadRequest.setDescription(imageUrl);
3244 // Show the download notification after the download is completed.
3245 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3247 // Remove the lint warning below that `downloadManager` might be `null`.
3248 assert downloadManager != null;
3250 // Initiate the download.
3251 downloadManager.enqueue(downloadRequest);
3252 } else { // The image is not an HTTP or HTTPS URI.
3253 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3258 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3259 // Download the file if it has an HTTP or HTTPS URI.
3260 if (downloadUrl.startsWith("http")) {
3261 // Get a handle for the system `DOWNLOAD_SERVICE`.
3262 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3264 // Parse `downloadUrl`.
3265 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3267 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3268 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3269 if (firstPartyCookiesEnabled) {
3270 // Get the cookies for `downloadUrl`.
3271 String cookies = cookieManager.getCookie(downloadUrl);
3273 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3274 downloadRequest.addRequestHeader("Cookie", cookies);
3277 // Get the file name from the dialog fragment.
3278 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3279 String fileName = downloadFileNameEditText.getText().toString();
3281 // Specify the download location.
3282 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3283 // Download to the public download directory.
3284 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3285 } else { // External write permission denied.
3286 // Download to the app's external download directory.
3287 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3290 // Allow `MediaScanner` to index the download if it is a media file.
3291 downloadRequest.allowScanningByMediaScanner();
3293 // Add the URL as the description for the download.
3294 downloadRequest.setDescription(downloadUrl);
3296 // Show the download notification after the download is completed.
3297 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3299 // Remove the lint warning below that `downloadManager` might be `null`.
3300 assert downloadManager != null;
3302 // Initiate the download.
3303 downloadManager.enqueue(downloadRequest);
3304 } else { // The download is not an HTTP or HTTPS URI.
3305 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3310 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3311 // Get handles for the views from `dialogFragment`.
3312 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3313 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3314 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3316 // Store the bookmark strings.
3317 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3318 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3320 // Update the bookmark.
3321 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3322 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3323 } else { // Update the bookmark using the `WebView` favorite icon.
3324 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3325 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3326 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3327 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3329 // Update the bookmark and the favorite icon.
3330 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3333 // Update `bookmarksCursor` with the current contents of this folder.
3334 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3336 // Update the `ListView`.
3337 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3341 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3342 // Get handles for the views from `dialogFragment`.
3343 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3344 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3345 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3346 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3348 // Get the new folder name.
3349 String newFolderNameString = editFolderNameEditText.getText().toString();
3351 // Check if the favorite icon has changed.
3352 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3353 // Update the name in the database.
3354 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3355 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3356 // Get the new folder icon `Bitmap`.
3357 Bitmap folderIconBitmap;
3358 if (defaultFolderIconRadioButton.isChecked()) {
3359 // Get the default folder icon and convert it to a `Bitmap`.
3360 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3361 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3362 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3363 } else { // Use the `WebView` favorite icon.
3364 folderIconBitmap = favoriteIconBitmap;
3367 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3368 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3369 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3370 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3372 // Update the folder icon in the database.
3373 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3374 } else { // The folder icon and the name have changed.
3375 // Get the new folder icon `Bitmap`.
3376 Bitmap folderIconBitmap;
3377 if (defaultFolderIconRadioButton.isChecked()) {
3378 // Get the default folder icon and convert it to a `Bitmap`.
3379 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3380 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3381 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3382 } else { // Use the `WebView` favorite icon.
3383 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3386 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3387 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3388 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3389 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3391 // Update the folder name and icon in the database.
3392 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3395 // Update `bookmarksCursor` with the current contents of this folder.
3396 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3398 // Update the `ListView`.
3399 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3403 public void onHttpAuthenticationCancel() {
3404 // Cancel the `HttpAuthHandler`.
3405 httpAuthHandler.cancel();
3409 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3410 // Get handles for the `EditTexts`.
3411 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3412 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3414 // Proceed with the HTTP authentication.
3415 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3418 public void viewSslCertificate(View view) {
3419 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3420 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3421 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3425 public void onSslErrorCancel() {
3426 sslErrorHandler.cancel();
3430 public void onSslErrorProceed() {
3431 sslErrorHandler.proceed();
3435 public void onSslMismatchBack() {
3436 if (mainWebView.canGoBack()) { // There is a back page in the history.
3437 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3438 formattedUrlString = "";
3440 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3441 navigatingHistory = true;
3444 mainWebView.goBack();
3445 } else { // There are no pages to go back to.
3446 // Load a blank page
3452 public void onSslMismatchProceed() {
3453 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3454 ignorePinnedSslCertificate = true;
3458 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3459 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3460 formattedUrlString = "";
3462 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3463 navigatingHistory = true;
3465 // Load the history entry.
3466 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3470 public void onClearHistory() {
3471 // Clear the history.
3472 mainWebView.clearHistory();
3475 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3477 public void onBackPressed() {
3478 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3479 // Close the navigation drawer.
3480 drawerLayout.closeDrawer(GravityCompat.START);
3481 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3482 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3483 // close the bookmarks drawer.
3484 drawerLayout.closeDrawer(GravityCompat.END);
3485 } else { // A subfolder is displayed.
3486 // Place the former parent folder in `currentFolder`.
3487 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3489 // Load the new folder.
3490 loadBookmarksFolder();
3493 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3494 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3495 formattedUrlString = "";
3497 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3498 navigatingHistory = true;
3501 mainWebView.goBack();
3502 } else { // There isn't anything to do in Privacy Browser.
3503 // Pass `onBackPressed()` to the system.
3504 super.onBackPressed();
3508 // 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.
3510 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3511 // File uploads only work on API >= 21.
3512 if (Build.VERSION.SDK_INT >= 21) {
3513 // Pass the file to the WebView.
3514 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3518 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3519 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3520 String unformattedUrlString = urlTextBox.getText().toString().trim();
3522 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3523 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3524 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3525 if (!unformattedUrlString.startsWith("http")) {
3526 unformattedUrlString = "http://" + unformattedUrlString;
3529 // Initialize `unformattedUrl`.
3530 URL unformattedUrl = null;
3532 // 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.
3534 unformattedUrl = new URL(unformattedUrlString);
3535 } catch (MalformedURLException e) {
3536 e.printStackTrace();
3539 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3540 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3541 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3542 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3543 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3544 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3547 Uri.Builder formattedUri = new Uri.Builder();
3548 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3550 // Decode `formattedUri` as a `String` in `UTF-8`.
3551 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3552 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3553 // Load a blank string.
3554 formattedUrlString = "";
3555 } else { // Search for the contents of the URL box.
3556 // Sanitize the search input and convert it to a search.
3557 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3559 // Add the base search URL.
3560 formattedUrlString = searchURL + encodedUrlString;
3563 // 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.
3564 urlTextBox.clearFocus();
3567 loadUrl(formattedUrlString);
3570 private void loadUrl(String url) {// Apply any custom domain settings.
3571 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3572 formattedUrlString = url;
3574 // Apply the domain settings.
3575 applyDomainSettings(url, true, false);
3577 // If loading a website, set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3578 urlIsLoading = !url.equals("");
3581 mainWebView.loadUrl(url, customHeaders);
3584 public void findPreviousOnPage(View view) {
3585 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3586 mainWebView.findNext(false);
3589 public void findNextOnPage(View view) {
3590 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3591 mainWebView.findNext(true);
3594 public void closeFindOnPage(View view) {
3595 // Delete the contents of `find_on_page_edittext`.
3596 findOnPageEditText.setText(null);
3598 // Clear the highlighted phrases.
3599 mainWebView.clearMatches();
3601 // Hide the Find on Page `RelativeLayout`.
3602 findOnPageLinearLayout.setVisibility(View.GONE);
3604 // Show the URL app bar.
3605 supportAppBar.setVisibility(View.VISIBLE);
3607 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3608 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3611 private void applyAppSettings() {
3612 // Get a handle for the shared preferences.
3613 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3615 // Store the values from the shared preferences in variables.
3616 String homepageString = sharedPreferences.getString("homepage", "https://searx.me/");
3617 String torHomepageString = sharedPreferences.getString("tor_homepage", "http://ulrn6sryqaifefld.onion/");
3618 String torSearchString = sharedPreferences.getString("tor_search", "http://ulrn6sryqaifefld.onion/?q=");
3619 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3620 String searchString = sharedPreferences.getString("search", "https://searx.me/?q=");
3621 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3622 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3623 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3624 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3625 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3626 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3627 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3628 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3630 // Set the homepage, search, and proxy options.
3631 if (proxyThroughOrbot) { // Set the Tor options.
3632 // Set `torHomepageString` as `homepage`.
3633 homepage = torHomepageString;
3635 // If formattedUrlString is null assign the homepage to it.
3636 if (formattedUrlString == null) {
3637 formattedUrlString = homepage;
3640 // Set the search URL.
3641 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3642 searchURL = torSearchCustomURLString;
3643 } else { // Use the string from the pre-built list.
3644 searchURL = torSearchString;
3647 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3648 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3650 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3652 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3654 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3657 // Display a message to the user if waiting for Orbot.
3658 if (!orbotStatus.equals("ON")) {
3659 // Set `waitingForOrbot`.
3660 waitingForOrbot = true;
3662 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3663 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3665 } else { // Set the non-Tor options.
3666 // Set `homepageString` as `homepage`.
3667 homepage = homepageString;
3669 // If formattedUrlString is null assign the homepage to it.
3670 if (formattedUrlString == null) {
3671 formattedUrlString = homepage;
3674 // Set the search URL.
3675 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3676 searchURL = searchCustomURLString;
3677 } else { // Use the string from the pre-built list.
3678 searchURL = searchString;
3681 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3682 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3684 // Set the default `appBar` background. `this` refers to the context.
3686 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3688 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3691 // Reset `waitingForOrbot.
3692 waitingForOrbot = false;
3695 // Set Do Not Track status.
3696 if (doNotTrackEnabled) {
3697 customHeaders.put("DNT", "1");
3699 customHeaders.remove("DNT");
3702 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3703 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3704 if (hideSystemBarsOnFullscreen) { // Hide everything.
3705 // Remove the translucent navigation setting if it is currently flagged.
3706 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3708 // Remove the translucent status bar overlay.
3709 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3711 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3712 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3714 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3715 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3716 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3718 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3719 } else { // Hide everything except the status and navigation bars.
3720 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3721 rootCoordinatorLayout.setSystemUiVisibility(0);
3723 // Add the translucent status flag if it is unset.
3724 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3726 if (translucentNavigationBarOnFullscreen) {
3727 // Set the navigation bar to be translucent.
3728 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3730 // Set the navigation bar to be black.
3731 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3734 } else { // Privacy Browser is not in full screen browsing mode.
3735 // 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.
3736 inFullScreenBrowsingMode = false;
3738 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3739 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3743 // Show the `BannerAd` in the free flavor.
3744 if (BuildConfig.FLAVOR.contentEquals("free")) {
3745 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3746 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3749 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3750 rootCoordinatorLayout.setSystemUiVisibility(0);
3752 // Remove the translucent navigation bar flag if it is set.
3753 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3755 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3756 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3758 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3759 rootCoordinatorLayout.setFitsSystemWindows(true);
3763 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3764 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3765 @SuppressWarnings("deprecation")
3766 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3767 // Parse the URL into a URI.
3768 Uri uri = Uri.parse(url);
3770 // Extract the domain from `uri`.
3771 String hostName = uri.getHost();
3773 // Initialize `loadingNewDomainName`.
3774 boolean loadingNewDomainName;
3776 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3777 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3778 //noinspection SimplifiableIfStatement
3779 if ((hostName == null) || (currentDomainName == null)) {
3780 loadingNewDomainName = true;
3781 } else { // Determine if `hostName` equals `currentDomainName`.
3782 loadingNewDomainName = !hostName.equals(currentDomainName);
3785 // Strings don't like to be null.
3786 if (hostName == null) {
3790 // 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.
3791 if (loadingNewDomainName) {
3792 // Set the new `hostname` as the `currentDomainName`.
3793 currentDomainName = hostName;
3795 // Reset `ignorePinnedSslCertificate`.
3796 ignorePinnedSslCertificate = false;
3798 // Reset the favorite icon if specified.
3799 if (resetFavoriteIcon) {
3800 favoriteIconBitmap = favoriteIconDefaultBitmap;
3801 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3804 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3805 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3806 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3808 // Get a full cursor from `domainsDatabaseHelper`.
3809 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3811 // Initialize `domainSettingsSet`.
3812 Set<String> domainSettingsSet = new HashSet<>();
3814 // Get the domain name column index.
3815 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3817 // Populate `domainSettingsSet`.
3818 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3819 // Move `domainsCursor` to the current row.
3820 domainNameCursor.moveToPosition(i);
3822 // Store the domain name in `domainSettingsSet`.
3823 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3826 // Close `domainNameCursor.
3827 domainNameCursor.close();
3829 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3830 domainSettingsApplied = false;
3831 String domainNameInDatabase = null;
3833 // Check the hostname.
3834 if (domainSettingsSet.contains(hostName)) {
3835 domainSettingsApplied = true;
3836 domainNameInDatabase = hostName;
3839 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3840 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3841 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3842 // Apply the domain settings.
3843 domainSettingsApplied = true;
3845 // Store the applied domain names as it appears in the database.
3846 domainNameInDatabase = "*." + hostName;
3849 // Strip out the lowest subdomain of of the host name.
3850 hostName = hostName.substring(hostName.indexOf(".") + 1);
3854 // Get a handle for the shared preference.
3855 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3857 // Store the general preference information.
3858 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3859 String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3860 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3861 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3862 nightMode = sharedPreferences.getBoolean("night_mode", false);
3864 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3865 // Get a cursor for the current host and move it to the first position.
3866 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3867 currentHostDomainSettingsCursor.moveToFirst();
3869 // Get the settings from the cursor.
3870 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3871 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3872 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3873 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3874 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3875 // Form data can be removed once the minimum API >= 26.
3876 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3877 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3878 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3879 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3880 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3881 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3882 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3883 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3884 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3885 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3886 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3887 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3888 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3889 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3890 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3891 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3892 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3893 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3894 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3896 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3897 switch (nightModeInt) {
3898 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3902 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3907 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3909 javaScriptEnabled = true;
3912 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3913 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3914 pinnedDomainSslStartDate = null;
3916 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3919 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3920 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3921 pinnedDomainSslEndDate = null;
3923 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3926 // Close `currentHostDomainSettingsCursor`.
3927 currentHostDomainSettingsCursor.close();
3929 // Apply the domain settings.
3930 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3931 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3932 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3934 // Apply the form data setting if the API < 26.
3935 if (Build.VERSION.SDK_INT < 26) {
3936 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3939 // Apply the font size.
3940 if (fontSize == 0) { // Apply the default font size.
3941 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3942 } else { // Apply the specified font size.
3943 mainWebView.getSettings().setTextZoom(fontSize);
3946 // Set third-party cookies status if API >= 21.
3947 if (Build.VERSION.SDK_INT >= 21) {
3948 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3951 // 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.
3952 // <https://redmine.stoutner.com/issues/160>
3953 if (!urlIsLoading) {
3954 // Set the user agent.
3955 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3956 // Get the array position of the default user agent name.
3957 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3959 // Set the user agent according to the system default.
3960 switch (defaultUserAgentArrayPosition) {
3961 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3962 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3963 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3966 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3967 // Set the user agent to `""`, which uses the default value.
3968 mainWebView.getSettings().setUserAgentString("");
3971 case SETTINGS_CUSTOM_USER_AGENT:
3972 // Set the custom user agent.
3973 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3977 // Get the user agent string from the user agent data array
3978 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3980 } else { // Set the user agent according to the stored name.
3981 // Get the array position of the user agent name.
3982 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3984 switch (userAgentArrayPosition) {
3985 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3986 mainWebView.getSettings().setUserAgentString(userAgentName);
3989 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3990 // Set the user agent to `""`, which uses the default value.
3991 mainWebView.getSettings().setUserAgentString("");
3995 // Get the user agent string from the user agent data array.
3996 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4000 // Set swipe to refresh.
4001 switch (swipeToRefreshInt) {
4002 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
4003 // Set swipe to refresh according to the default.
4004 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4007 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
4008 // Enable swipe to refresh.
4009 swipeRefreshLayout.setEnabled(true);
4012 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
4013 // Disable swipe to refresh.
4014 swipeRefreshLayout.setEnabled(false);
4017 // Store the applied user agent string, which is used in the View Source activity.
4018 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4021 // 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.
4023 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4025 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4027 } else { // The new URL does not have custom domain settings. Load the defaults.
4028 // Store the values from `sharedPreferences` in variables.
4029 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
4030 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
4031 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
4032 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
4033 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false); // Form data can be removed once the minimum API >= 26.
4034 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
4035 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
4036 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
4037 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
4038 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
4039 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
4041 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4043 javaScriptEnabled = true;
4046 // Apply the default settings.
4047 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4048 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4049 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4050 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4051 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4053 // Apply the form data setting if the API < 26.
4054 if (Build.VERSION.SDK_INT < 26) {
4055 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4058 // Reset the pinned SSL certificate information.
4059 domainSettingsDatabaseId = -1;
4060 pinnedDomainSslCertificate = false;
4061 pinnedDomainSslIssuedToCNameString = "";
4062 pinnedDomainSslIssuedToONameString = "";
4063 pinnedDomainSslIssuedToUNameString = "";
4064 pinnedDomainSslIssuedByCNameString = "";
4065 pinnedDomainSslIssuedByONameString = "";
4066 pinnedDomainSslIssuedByUNameString = "";
4067 pinnedDomainSslStartDate = null;
4068 pinnedDomainSslEndDate = null;
4070 // Set third-party cookies status if API >= 21.
4071 if (Build.VERSION.SDK_INT >= 21) {
4072 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4075 // 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.
4076 // <https://redmine.stoutner.com/issues/160>
4077 if (!urlIsLoading) {
4078 // Get the array position of the user agent name.
4079 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4081 // Set the user agent.
4082 switch (userAgentArrayPosition) {
4083 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4084 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4085 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4088 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4089 // Set the user agent to `""`, which uses the default value.
4090 mainWebView.getSettings().setUserAgentString("");
4093 case SETTINGS_CUSTOM_USER_AGENT:
4094 // Set the custom user agent.
4095 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4099 // Get the user agent string from the user agent data array
4100 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4103 // Store the applied user agent string, which is used in the View Source activity.
4104 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4107 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4108 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4111 // Close `domainsDatabaseHelper`.
4112 domainsDatabaseHelper.close();
4114 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
4115 onTheFlyDisplayImagesSet = false;
4116 setDisplayWebpageImages();
4118 // Update the privacy icons, but only if `mainMenu` has already been populated.
4119 if (mainMenu != null) {
4120 updatePrivacyIcons(true);
4124 // Reload the website if returning from the Domains activity.
4125 if (reloadWebsite) {
4126 mainWebView.reload();
4130 private void setDisplayWebpageImages() {
4131 if (!onTheFlyDisplayImagesSet) {
4132 if (domainSettingsApplied) { // Custom domain settings are applied.
4133 switch (displayWebpageImagesInt) {
4134 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4135 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4138 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4139 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4142 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4143 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4146 } else { // Default settings are applied.
4147 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4152 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4153 // Get handles for the menu items.
4154 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4155 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4156 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4157 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4159 // Update the privacy icon.
4160 if (javaScriptEnabled) { // JavaScript is enabled.
4161 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4162 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4163 privacyMenuItem.setIcon(R.drawable.warning);
4164 } else { // All the dangerous features are disabled.
4165 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4168 // Update the first-party cookies icon.
4169 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4170 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4171 } else { // First-party cookies are disabled.
4173 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4175 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4179 // Update the DOM storage icon.
4180 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4181 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4182 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4184 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4186 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4188 } else { // JavaScript is disabled, so DOM storage is ghosted.
4190 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4192 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4196 // Update the refresh icon.
4198 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4200 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4203 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4204 if (runInvalidateOptionsMenu) {
4205 invalidateOptionsMenu();
4209 private void highlightUrlText() {
4210 String urlString = urlTextBox.getText().toString();
4212 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4213 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4214 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4215 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4218 // Get the index of the `/` immediately after the domain name.
4219 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4221 // De-emphasize the text after the domain name.
4222 if (endOfDomainName > 0) {
4223 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4227 private void loadBookmarksFolder() {
4228 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4229 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4231 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4232 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4234 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4235 // Inflate the individual item layout. `false` does not attach it to the root.
4236 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4240 public void bindView(View view, Context context, Cursor cursor) {
4241 // Get handles for the views.
4242 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4243 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4245 // Get the favorite icon byte array from the cursor.
4246 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4248 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4249 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4251 // Display the bitmap in `bookmarkFavoriteIcon`.
4252 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4254 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4255 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4256 bookmarkNameTextView.setText(bookmarkNameString);
4258 // Make the font bold for folders.
4259 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4260 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4261 } else { // Reset the font to default for normal bookmarks.
4262 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4267 // Populate the `ListView` with the adapter.
4268 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4270 // Set the bookmarks drawer title.
4271 if (currentBookmarksFolder.isEmpty()) {
4272 bookmarksTitleTextView.setText(R.string.bookmarks);
4274 bookmarksTitleTextView.setText(currentBookmarksFolder);