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.Activity;
27 import android.app.DialogFragment;
28 import android.app.DownloadManager;
29 import android.app.SearchManager;
30 import android.content.ActivityNotFoundException;
31 import android.content.BroadcastReceiver;
32 import android.content.ClipData;
33 import android.content.ClipboardManager;
34 import android.content.Context;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.SharedPreferences;
38 import android.content.pm.PackageManager;
39 import android.content.res.Configuration;
40 import android.content.res.Resources;
41 import android.database.Cursor;
42 import android.graphics.Bitmap;
43 import android.graphics.BitmapFactory;
44 import android.graphics.Typeface;
45 import android.graphics.drawable.BitmapDrawable;
46 import android.graphics.drawable.Drawable;
47 import android.net.Uri;
48 import android.net.http.SslCertificate;
49 import android.net.http.SslError;
50 import android.os.Build;
51 import android.os.Bundle;
52 import android.os.Environment;
53 import android.os.Handler;
54 import android.preference.PreferenceManager;
55 import android.print.PrintDocumentAdapter;
56 import android.print.PrintManager;
57 import android.support.annotation.NonNull;
58 import android.support.design.widget.CoordinatorLayout;
59 import android.support.design.widget.FloatingActionButton;
60 import android.support.design.widget.NavigationView;
61 import android.support.design.widget.Snackbar;
62 import android.support.v4.app.ActivityCompat;
63 import android.support.v4.content.ContextCompat;
64 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
65 import android.support.v4.content.pm.ShortcutInfoCompat;
66 import android.support.v4.content.pm.ShortcutManagerCompat;
67 import android.support.v4.graphics.drawable.IconCompat;
68 import android.support.v4.view.GravityCompat;
69 import android.support.v4.widget.DrawerLayout;
70 import android.support.v4.widget.SwipeRefreshLayout;
71 import android.support.v7.app.ActionBar;
72 import android.support.v7.app.ActionBarDrawerToggle;
73 import android.support.v7.app.AppCompatActivity;
74 import android.support.v7.app.AppCompatDialogFragment;
75 import android.support.v7.widget.Toolbar;
76 import android.text.Editable;
77 import android.text.Spanned;
78 import android.text.TextWatcher;
79 import android.text.style.ForegroundColorSpan;
80 import android.util.Patterns;
81 import android.view.ContextMenu;
82 import android.view.GestureDetector;
83 import android.view.KeyEvent;
84 import android.view.Menu;
85 import android.view.MenuItem;
86 import android.view.MotionEvent;
87 import android.view.View;
88 import android.view.ViewGroup;
89 import android.view.WindowManager;
90 import android.view.inputmethod.InputMethodManager;
91 import android.webkit.CookieManager;
92 import android.webkit.HttpAuthHandler;
93 import android.webkit.SslErrorHandler;
94 import android.webkit.ValueCallback;
95 import android.webkit.WebBackForwardList;
96 import android.webkit.WebChromeClient;
97 import android.webkit.WebResourceResponse;
98 import android.webkit.WebStorage;
99 import android.webkit.WebView;
100 import android.webkit.WebViewClient;
101 import android.webkit.WebViewDatabase;
102 import android.widget.ArrayAdapter;
103 import android.widget.CursorAdapter;
104 import android.widget.EditText;
105 import android.widget.FrameLayout;
106 import android.widget.ImageView;
107 import android.widget.LinearLayout;
108 import android.widget.ListView;
109 import android.widget.ProgressBar;
110 import android.widget.RadioButton;
111 import android.widget.RelativeLayout;
112 import android.widget.TextView;
114 import com.stoutner.privacybrowser.BuildConfig;
115 import com.stoutner.privacybrowser.R;
116 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
117 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
118 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
119 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
120 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
121 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
122 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
123 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
124 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
125 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
126 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
127 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
128 import com.stoutner.privacybrowser.helpers.AdHelper;
129 import com.stoutner.privacybrowser.helpers.BlockListHelper;
130 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
131 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
132 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
133 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
134 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
136 import java.io.ByteArrayInputStream;
137 import java.io.ByteArrayOutputStream;
139 import java.io.IOException;
140 import java.io.UnsupportedEncodingException;
141 import java.net.MalformedURLException;
143 import java.net.URLDecoder;
144 import java.net.URLEncoder;
145 import java.util.ArrayList;
146 import java.util.Date;
147 import java.util.HashMap;
148 import java.util.HashSet;
149 import java.util.List;
150 import java.util.Map;
151 import java.util.Set;
153 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
154 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
155 CreateHomeScreenShortcutDialog.CreateHomeScreenShortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
156 DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
157 HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
158 SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
160 // `darkTheme` is public static so it can be accessed from everywhere.
161 public static boolean darkTheme;
163 // `allowScreenshots` is public static so it can be accessed from everywhere. It is also used in `onCreate()`.
164 public static boolean allowScreenshots;
166 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
167 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
168 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
169 public static Bitmap favoriteIconBitmap;
171 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
172 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, `loadUrlFromTextBox()`, and `applyProxyThroughOrbot()`.
173 public static String formattedUrlString;
175 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
176 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
177 public static SslCertificate sslCertificate;
179 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
180 public static String orbotStatus;
182 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
183 public static String webViewTitle;
185 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
186 public static String appliedUserAgentString;
188 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
189 public static boolean reloadOnRestart;
191 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`. It is also used in `onRestart()`.
192 public static boolean loadUrlOnRestart;
194 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
195 public static boolean restartFromBookmarksActivity;
197 // The block list versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
198 public static String easyListVersion;
199 public static String easyPrivacyVersion;
200 public static String fanboysAnnoyanceVersion;
201 public static String fanboysSocialVersion;
202 public static String ultraPrivacyVersion;
204 // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`. They are also used in `onCreate()` and `onPrepareOptionsMenu()`.
205 public static List<String[]> resourceRequests;
206 public static String[] whiteListResultStringArray;
207 private int blockedRequests;
208 private int easyListBlockedRequests;
209 private int easyPrivacyBlockedRequests;
210 private int fanboysAnnoyanceListBlockedRequests;
211 private int fanboysSocialBlockingListBlockedRequests;
212 private int ultraPrivacyBlockedRequests;
213 private int thirdPartyBlockedRequests;
215 public final static int REQUEST_DISPOSITION = 0;
216 public final static int REQUEST_URL = 1;
217 public final static int REQUEST_BLOCKLIST = 2;
218 public final static int REQUEST_SUBLIST = 3;
219 public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
220 public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
222 public final static int REQUEST_DEFAULT = 0;
223 public final static int REQUEST_ALLOWED = 1;
224 public final static int REQUEST_THIRD_PARTY = 2;
225 public final static int REQUEST_BLOCKED = 3;
227 public final static int MAIN_WHITELIST = 1;
228 public final static int FINAL_WHITELIST = 2;
229 public final static int DOMAIN_WHITELIST = 3;
230 public final static int DOMAIN_INITIAL_WHITELIST = 4;
231 public final static int DOMAIN_FINAL_WHITELIST = 5;
232 public final static int THIRD_PARTY_WHITELIST = 6;
233 public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
234 public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
236 public final static int MAIN_BLACKLIST = 9;
237 public final static int INITIAL_BLACKLIST = 10;
238 public final static int FINAL_BLACKLIST = 11;
239 public final static int DOMAIN_BLACKLIST = 12;
240 public final static int DOMAIN_INITIAL_BLACKLIST = 13;
241 public final static int DOMAIN_FINAL_BLACKLIST = 14;
242 public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
243 public final static int THIRD_PARTY_BLACKLIST = 16;
244 public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
245 public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
246 public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
247 public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
248 public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
249 public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
251 // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
252 // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
253 public static boolean blockAllThirdPartyRequests;
255 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
256 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
257 public static String currentBookmarksFolder;
259 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
260 public static int domainSettingsDatabaseId;
262 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
263 public static String pinnedDomainSslIssuedToCNameString;
264 public static String pinnedDomainSslIssuedToONameString;
265 public static String pinnedDomainSslIssuedToUNameString;
266 public static String pinnedDomainSslIssuedByCNameString;
267 public static String pinnedDomainSslIssuedByONameString;
268 public static String pinnedDomainSslIssuedByUNameString;
269 public static Date pinnedDomainSslStartDate;
270 public static Date pinnedDomainSslEndDate;
272 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
273 public final static int UNRECOGNIZED_USER_AGENT = -1;
274 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
275 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
276 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
277 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
278 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
281 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
282 private ActionBar appBar;
284 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
285 private boolean navigatingHistory;
287 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
288 private Bitmap favoriteIconDefaultBitmap;
290 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
291 private DrawerLayout drawerLayout;
293 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
294 private CoordinatorLayout rootCoordinatorLayout;
296 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
297 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `applyProxyThroughOrbot()`.
298 private WebView mainWebView;
300 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
301 private FrameLayout fullScreenVideoFrameLayout;
303 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
304 private SwipeRefreshLayout swipeRefreshLayout;
306 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
307 private RelativeLayout urlAppBarRelativeLayout;
309 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
310 private ImageView favoriteIconImageView;
312 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
313 private CookieManager cookieManager;
315 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
316 private final Map<String, String> customHeaders = new HashMap<>();
318 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
319 private boolean javaScriptEnabled;
321 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
322 private boolean firstPartyCookiesEnabled;
324 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
325 private boolean thirdPartyCookiesEnabled;
327 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
328 private boolean domStorageEnabled;
330 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`. It can be removed once the minimum API >= 26.
331 private boolean saveFormDataEnabled;
333 // `nightMode` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
334 private boolean nightMode;
336 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyProxyThroughOrbot()`.
337 private String homepage;
339 // `searchURL` is used in `loadURLFromTextBox()` and `applyProxyThroughOrbot()`.
340 private String searchURL;
342 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
343 private Menu mainMenu;
345 // `refreshMenuItem` is used in `onCreate()` and `onCreateOptionsMenu()`.
346 private MenuItem refreshMenuItem;
348 // The blocklist menu items are used in `onCreate()`, `onCreateOptionsMenu()`, and `onPrepareOptionsMenu()`.
349 private MenuItem blocklistsMenuItem;
350 private MenuItem easyListMenuItem;
351 private MenuItem easyPrivacyMenuItem;
352 private MenuItem fanboysAnnoyanceListMenuItem;
353 private MenuItem fanboysSocialBlockingListMenuItem;
354 private MenuItem ultraPrivacyMenuItem;
355 private MenuItem blockAllThirdPartyRequestsMenuItem;
357 // The blocklist variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
358 private boolean easyListEnabled;
359 private boolean easyPrivacyEnabled;
360 private boolean fanboysAnnoyanceListEnabled;
361 private boolean fanboysSocialBlockingListEnabled;
362 private boolean ultraPrivacyEnabled;
364 // `webViewDefaultUserAgent` is used in `onCreate()` and `onPrepareOptionsMenu()`.
365 private String webViewDefaultUserAgent;
367 // `defaultCustomUserAgentString` is used in `onPrepareOptionsMenu()` and `applyDomainSettings()`.
368 private String defaultCustomUserAgentString;
370 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
371 private Runtime privacyBrowserRuntime;
373 // `proxyThroughOrbot` is used in `onRestart()`, `onOptionsItemSelected()`, `applyAppSettings()`, and `applyProxyThroughOrbot()`.
374 private boolean proxyThroughOrbot;
376 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
377 private boolean incognitoModeEnabled;
379 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
380 private boolean fullScreenBrowsingModeEnabled;
382 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
383 private boolean inFullScreenBrowsingMode;
385 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
386 private boolean hideSystemBarsOnFullscreen;
388 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
389 private boolean translucentNavigationBarOnFullscreen;
391 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
392 private boolean reapplyDomainSettingsOnRestart;
394 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
395 private boolean reapplyAppSettingsOnRestart;
397 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
398 private boolean displayingFullScreenVideo;
400 // `downloadWithExternalApp` is used in `onCreate()`, `onCreateContextMenu()`, and `applyDomainSettings()`.
401 private boolean downloadWithExternalApp;
403 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
404 private String currentDomainName;
406 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
407 private boolean ignorePinnedSslCertificate;
409 // `orbotStatusBroadcastReceiver` is used in `onCreate()` and `onDestroy()`.
410 private BroadcastReceiver orbotStatusBroadcastReceiver;
412 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyProxyThroughOrbot()`.
413 private boolean waitingForOrbot;
415 // `domainSettingsApplied` is used in `prepareOptionsMenu()` and `applyDomainSettings()`.
416 private boolean domainSettingsApplied;
418 // `domainSettingsJavaScriptEnabled` is used in `onOptionsItemSelected()` and `applyDomainSettings()`.
419 private Boolean domainSettingsJavaScriptEnabled;
421 // `waitingForOrbotHtmlString` is used in `onCreate()` and `applyProxyThroughOrbot()`.
422 private String waitingForOrbotHtmlString;
424 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
425 private String privateDataDirectoryString;
427 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
428 private LinearLayout findOnPageLinearLayout;
430 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
431 private EditText findOnPageEditText;
433 // `displayAdditionalAppBarIcons` is used in `onCreate()` and `onCreateOptionsMenu()`.
434 private boolean displayAdditionalAppBarIcons;
436 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
437 private ActionBarDrawerToggle drawerToggle;
439 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
440 private Toolbar supportAppBar;
442 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
443 private EditText urlTextBox;
445 // The color spans are used in `onCreate()` and `highlightUrlText()`.
446 private ForegroundColorSpan redColorSpan;
447 private ForegroundColorSpan initialGrayColorSpan;
448 private ForegroundColorSpan finalGrayColorSpan;
450 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
451 private SslErrorHandler sslErrorHandler;
453 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
454 private static HttpAuthHandler httpAuthHandler;
456 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
457 private InputMethodManager inputMethodManager;
459 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
460 private RelativeLayout mainWebViewRelativeLayout;
462 // `urlIsLoading` is used in `onCreate()`, `onCreateOptionsMenu()`, `loadUrl()`, and `applyDomainSettings()`.
463 private boolean urlIsLoading;
465 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
466 private boolean pinnedDomainSslCertificate;
468 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onDestroy`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`,
469 // and `loadBookmarksFolder()`.
470 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
472 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
473 private ListView bookmarksListView;
475 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
476 private TextView bookmarksTitleTextView;
478 // `bookmarksCursor` is used in `onDestroy()`, `onOptionsItemSelected()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
479 private Cursor bookmarksCursor;
481 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
482 private CursorAdapter bookmarksCursorAdapter;
484 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
485 private String oldFolderNameString;
487 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
488 private ValueCallback<Uri[]> fileChooserCallback;
490 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
491 private String downloadUrl;
492 private String downloadContentDisposition;
493 private long downloadContentLength;
495 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
496 private String downloadImageUrl;
498 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
499 private ArrayAdapter<CharSequence> userAgentNamesArray;
500 private String[] userAgentDataArray;
502 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
503 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
504 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
507 // 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.
508 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
509 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
510 // Remove Android Studio's warning about deprecations. The deprecated `getColor()` must be used until API >= 23.
511 @SuppressWarnings("deprecation")
512 protected void onCreate(Bundle savedInstanceState) {
513 // Get a handle for the shared preferences.
514 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
516 // Get the theme and screenshot preferences.
517 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
518 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
520 // Disable screenshots if not allowed.
521 if (!allowScreenshots) {
522 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
525 // Set the activity theme.
527 setTheme(R.style.PrivacyBrowserDark);
529 setTheme(R.style.PrivacyBrowserLight);
532 // Run the default commands.
533 super.onCreate(savedInstanceState);
535 // Set the content view.
536 setContentView(R.layout.main_drawerlayout);
538 // Get a handle for the resources.
539 Resources resources = getResources();
541 // Get a handle for `inputMethodManager`.
542 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
544 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
545 supportAppBar = findViewById(R.id.app_bar);
546 setSupportActionBar(supportAppBar);
547 appBar = getSupportActionBar();
549 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
550 assert appBar != null;
552 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
553 appBar.setCustomView(R.layout.url_app_bar);
554 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
556 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
557 redColorSpan = new ForegroundColorSpan(resources.getColor(R.color.red_a700));
558 initialGrayColorSpan = new ForegroundColorSpan(resources.getColor(R.color.gray_500));
559 finalGrayColorSpan = new ForegroundColorSpan(resources.getColor(R.color.gray_500));
561 // Get a handle for `urlTextBox`.
562 urlTextBox = findViewById(R.id.url_edittext);
564 // Remove the formatting from `urlTextBar` when the user is editing the text.
565 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
566 if (hasFocus) { // The user is editing the URL text box.
567 // Remove the highlighting.
568 urlTextBox.getText().removeSpan(redColorSpan);
569 urlTextBox.getText().removeSpan(initialGrayColorSpan);
570 urlTextBox.getText().removeSpan(finalGrayColorSpan);
571 } else { // The user has stopped editing the URL text box.
572 // Move to the beginning of the string.
573 urlTextBox.setSelection(0);
575 // Reapply the highlighting.
580 // Set the go button on the keyboard to load the URL in `urlTextBox`.
581 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
582 // If the event is a key-down event on the `enter` button, load the URL.
583 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
584 // Load the URL into the mainWebView and consume the event.
585 loadUrlFromTextBox();
587 // If the enter key was pressed, consume the event.
590 // If any other key was pressed, do not consume the event.
595 // Set `waitingForOrbotHTMLString`.
596 waitingForOrbotHtmlString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
598 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
599 currentDomainName = "";
600 orbotStatus = "unknown";
601 waitingForOrbot = false;
603 // Create an Orbot status `BroadcastReceiver`.
604 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
606 public void onReceive(Context context, Intent intent) {
607 // Store the content of the status message in `orbotStatus`.
608 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
610 // If Privacy Browser is waiting on Orbot, load the website now that Orbot is connected.
611 if (orbotStatus.equals("ON") && waitingForOrbot) {
612 // Reset `waitingForOrbot`.
613 waitingForOrbot = false;
615 // Load `formattedUrlString
616 loadUrl(formattedUrlString);
621 // Register `orbotStatusBroadcastReceiver` on `this` context.
622 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
624 // Get handles for views that need to be accessed.
625 drawerLayout = findViewById(R.id.drawerlayout);
626 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
627 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
628 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
629 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
630 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
631 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
632 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
633 mainWebView = findViewById(R.id.main_webview);
634 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
635 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
636 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
637 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
638 favoriteIconImageView = findViewById(R.id.favorite_icon);
640 // 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.
642 launchBookmarksActivityFab.setImageDrawable(resources.getDrawable(R.drawable.bookmarks_dark));
643 createBookmarkFolderFab.setImageDrawable(resources.getDrawable(R.drawable.create_folder_dark));
644 createBookmarkFab.setImageDrawable(resources.getDrawable(R.drawable.create_bookmark_dark));
645 bookmarksListView.setBackgroundColor(resources.getColor(R.color.gray_850));
647 launchBookmarksActivityFab.setImageDrawable(resources.getDrawable(R.drawable.bookmarks_light));
648 createBookmarkFolderFab.setImageDrawable(resources.getDrawable(R.drawable.create_folder_light));
649 createBookmarkFab.setImageDrawable(resources.getDrawable(R.drawable.create_bookmark_light));
650 bookmarksListView.setBackgroundColor(resources.getColor(R.color.white));
653 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
654 launchBookmarksActivityFab.setOnClickListener(v -> {
655 // Create an intent to launch the bookmarks activity.
656 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
658 // Include the current folder with the `Intent`.
659 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
662 startActivity(bookmarksIntent);
665 // Set the create new bookmark folder FAB to display an alert dialog.
666 createBookmarkFolderFab.setOnClickListener(v -> {
667 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
668 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
669 createBookmarkFolderDialog.show(getSupportFragmentManager(), resources.getString(R.string.create_folder));
672 // Set the create new bookmark FAB to display an alert dialog.
673 createBookmarkFab.setOnClickListener(view -> {
674 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
675 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
676 createBookmarkDialog.show(getSupportFragmentManager(), resources.getString(R.string.create_bookmark));
679 // Create a double-tap listener to toggle full-screen mode.
680 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
681 // Override `onDoubleTap()`. All other events are handled using the default settings.
683 public boolean onDoubleTap(MotionEvent event) {
684 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
685 // Toggle `inFullScreenBrowsingMode`.
686 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
688 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
689 // Hide the `appBar`.
692 // Hide the banner ad in the free flavor.
693 if (BuildConfig.FLAVOR.contentEquals("free")) {
694 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
695 AdHelper.hideAd(findViewById(R.id.adview));
698 // Modify the system bars.
699 if (hideSystemBarsOnFullscreen) { // Hide everything.
700 // Remove the translucent overlays.
701 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
703 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
704 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
706 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
707 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
708 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
710 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
712 // Set `rootCoordinatorLayout` to fill the whole screen.
713 rootCoordinatorLayout.setFitsSystemWindows(false);
714 } else { // Hide everything except the status and navigation bars.
715 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
716 rootCoordinatorLayout.setFitsSystemWindows(false);
718 // 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.
719 if (translucentNavigationBarOnFullscreen) {
720 // Set the navigation bar to be translucent.
721 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
724 } else { // Switch to normal viewing mode.
725 // Show the `appBar`.
728 // Show the `BannerAd` in the free flavor.
729 if (BuildConfig.FLAVOR.contentEquals("free")) {
730 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
731 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
734 // Remove the translucent navigation bar flag if it is set.
735 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
737 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
738 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
740 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
741 rootCoordinatorLayout.setSystemUiVisibility(0);
743 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
744 rootCoordinatorLayout.setFitsSystemWindows(true);
747 // Consume the double-tap.
749 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
755 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
756 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
757 // Call `performClick()` on the view, which is required for accessibility.
760 // Send the `event` to `gestureDetector`.
761 return gestureDetector.onTouchEvent(event);
764 // Update `findOnPageCountTextView`.
765 mainWebView.setFindListener(new WebView.FindListener() {
766 // Get a handle for `findOnPageCountTextView`.
767 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
770 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
771 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
772 // Set `findOnPageCountTextView` to `0/0`.
773 findOnPageCountTextView.setText(R.string.zero_of_zero);
774 } else if (isDoneCounting) { // There are matches.
775 // `activeMatchOrdinal` is zero-based.
776 int activeMatch = activeMatchOrdinal + 1;
778 // Build the match string.
779 String matchString = activeMatch + "/" + numberOfMatches;
781 // Set `findOnPageCountTextView`.
782 findOnPageCountTextView.setText(matchString);
787 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
788 findOnPageEditText.addTextChangedListener(new TextWatcher() {
790 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
795 public void onTextChanged(CharSequence s, int start, int before, int count) {
800 public void afterTextChanged(Editable s) {
801 // Search for the text in `mainWebView`.
802 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
806 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
807 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
808 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
809 // Hide the soft keyboard. `0` indicates no additional flags.
810 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
812 // Consume the event.
814 } else { // A different key was pressed.
815 // Do not consume the event.
820 // Implement swipe to refresh.
821 swipeRefreshLayout = findViewById(R.id.swiperefreshlayout);
822 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
824 // Set the swipe to refresh color according to the theme.
826 swipeRefreshLayout.setColorSchemeResources(R.color.blue_600);
827 swipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.gray_850);
829 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
832 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
833 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
834 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
836 // Listen for touches on the navigation menu.
837 final NavigationView navigationView = findViewById(R.id.navigationview);
838 navigationView.setNavigationItemSelectedListener(this);
840 // 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.
841 final Menu navigationMenu = navigationView.getMenu();
842 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
843 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
844 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
845 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
847 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
848 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
849 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
851 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
852 currentBookmarksFolder = "";
854 // Load the home folder, which is `""` in the database.
855 loadBookmarksFolder();
857 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
858 // Convert the id from long to int to match the format of the bookmarks database.
859 int databaseID = (int) id;
861 // Get the bookmark cursor for this ID and move it to the first row.
862 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
863 bookmarkCursor.moveToFirst();
865 // Act upon the bookmark according to the type.
866 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
867 // Store the new folder name in `currentBookmarksFolder`.
868 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
870 // Load the new folder.
871 loadBookmarksFolder();
872 } else { // The selected bookmark is not a folder.
873 // Load the bookmark URL.
874 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
876 // Close the bookmarks drawer.
877 drawerLayout.closeDrawer(GravityCompat.END);
880 // Close the `Cursor`.
881 bookmarkCursor.close();
884 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
885 // Convert the database ID from `long` to `int`.
886 int databaseId = (int) id;
888 // Find out if the selected bookmark is a folder.
889 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
892 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
893 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
895 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
896 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
897 editFolderDialog.show(getSupportFragmentManager(), resources.getString(R.string.edit_folder));
899 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
900 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
901 editBookmarkDialog.show(getSupportFragmentManager(), resources.getString(R.string.edit_bookmark));
904 // Consume the event.
908 // Get the status bar pixel size.
909 int statusBarResourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
910 int statusBarPixelSize = resources.getDimensionPixelSize(statusBarResourceId);
912 // Get the resource density.
913 float screenDensity = resources.getDisplayMetrics().density;
915 // Calculate the drawer header padding. This is used to move the text in the drawer headers below any cutouts.
916 int drawerHeaderPaddingLeftAndRight = (int) (15 * screenDensity);
917 int drawerHeaderPaddingTop = statusBarPixelSize + (int) (4 * screenDensity);
918 int drawerHeaderPaddingBottom = (int) (8 * screenDensity);
920 // The drawer listener is used to update the navigation menu.
921 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
923 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
927 public void onDrawerOpened(@NonNull View drawerView) {
931 public void onDrawerClosed(@NonNull View drawerView) {
935 public void onDrawerStateChanged(int newState) {
936 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // A drawer is opening or closing.
937 // Get handles for the drawer headers.
938 TextView navigationHeaderTextView = findViewById(R.id.navigationText);
939 TextView bookmarksHeaderTextView = findViewById(R.id.bookmarks_title_textview);
941 // Apply the calculated drawer paddings. This moves the text in the header below any cutouts.
942 navigationHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
943 bookmarksHeaderTextView.setPadding(drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingTop, drawerHeaderPaddingLeftAndRight, drawerHeaderPaddingBottom);
945 // Update the back, forward, history, and requests menu items.
946 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
947 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
948 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
949 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
951 // Hide the keyboard (if displayed).
952 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
954 // Clear the focus from from the URL text box and the WebView. This removes any text selection markers and context menus, which otherwise draw above the open drawers.
955 urlTextBox.clearFocus();
956 mainWebView.clearFocus();
961 // drawerToggle creates the hamburger icon at the start of the AppBar.
962 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
964 // Get a handle for the progress bar.
965 final ProgressBar progressBar = findViewById(R.id.progress_bar);
967 mainWebView.setWebChromeClient(new WebChromeClient() {
968 // Update the progress bar when a page is loading.
970 public void onProgressChanged(WebView view, int progress) {
971 // Inject the night mode CSS if night mode is enabled.
973 // `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
974 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
975 // `border: none` removes all borders, which can also be used to underline text.
976 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
977 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
978 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
979 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
980 // Initialize a handler to display `mainWebView`.
981 Handler displayWebViewHandler = new Handler();
983 // Setup a runnable to display `mainWebView` after a delay to allow the CSS to be applied.
984 Runnable displayWebViewRunnable = () -> {
985 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
986 if (progressBar.getVisibility() == View.GONE) {
987 mainWebView.setVisibility(View.VISIBLE);
991 // Displaying of `mainWebView` after 500 milliseconds.
992 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
996 // Update the progress bar.
997 progressBar.setProgress(progress);
999 // Set the visibility of the progress bar.
1000 if (progress < 100) {
1001 // Show the progress bar.
1002 progressBar.setVisibility(View.VISIBLE);
1004 // Hide the progress bar.
1005 progressBar.setVisibility(View.GONE);
1007 // Display `mainWebView` if night mode is disabled.
1008 // 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
1009 // currently enabled.
1011 mainWebView.setVisibility(View.VISIBLE);
1014 //Stop the swipe to refresh indicator if it is running
1015 swipeRefreshLayout.setRefreshing(false);
1019 // Set the favorite icon when it changes.
1021 public void onReceivedIcon(WebView view, Bitmap icon) {
1022 // Only update the favorite icon if the website has finished loading.
1023 if (progressBar.getVisibility() == View.GONE) {
1024 // Save a copy of the favorite icon.
1025 favoriteIconBitmap = icon;
1027 // Place the favorite icon in the appBar.
1028 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1032 // Save a copy of the title when it changes.
1034 public void onReceivedTitle(WebView view, String title) {
1035 // Save a copy of the title.
1036 webViewTitle = title;
1039 // Enter full screen video.
1041 public void onShowCustomView(View view, CustomViewCallback callback) {
1042 // Set the full screen video flag.
1043 displayingFullScreenVideo = true;
1045 // Pause the ad if this is the free flavor.
1046 if (BuildConfig.FLAVOR.contentEquals("free")) {
1047 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1048 AdHelper.pauseAd(findViewById(R.id.adview));
1051 // Remove the translucent overlays.
1052 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1054 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1055 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1057 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1058 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1059 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1061 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1063 // Set `rootCoordinatorLayout` to fill the entire screen.
1064 rootCoordinatorLayout.setFitsSystemWindows(false);
1066 // Disable the sliding drawers.
1067 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1069 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1070 fullScreenVideoFrameLayout.addView(view);
1071 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1074 // Exit full screen video.
1076 public void onHideCustomView() {
1077 // Unset the full screen video flag.
1078 displayingFullScreenVideo = false;
1080 // Hide `fullScreenVideoFrameLayout`.
1081 fullScreenVideoFrameLayout.removeAllViews();
1082 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1084 // Enable the sliding drawers.
1085 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1087 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1088 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1089 if (hideSystemBarsOnFullscreen) { // Hide everything.
1090 // Remove the translucent navigation setting if it is currently flagged.
1091 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1093 // Remove the translucent status bar overlay.
1094 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1096 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1097 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1099 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1100 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1101 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1103 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1104 } else { // Hide everything except the status and navigation bars.
1105 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1106 rootCoordinatorLayout.setSystemUiVisibility(0);
1108 // Add the translucent status flag if it is unset.
1109 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1111 if (translucentNavigationBarOnFullscreen) {
1112 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1113 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1115 // Set the navigation bar to be black.
1116 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1119 } else { // Switch to normal viewing mode.
1120 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1121 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1125 // Show the `BannerAd` in the free flavor.
1126 if (BuildConfig.FLAVOR.contentEquals("free")) {
1127 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1128 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
1131 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1132 rootCoordinatorLayout.setSystemUiVisibility(0);
1134 // Remove the translucent navigation bar flag if it is set.
1135 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1137 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1138 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1140 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1141 rootCoordinatorLayout.setFitsSystemWindows(true);
1144 // Show the ad if this is the free flavor.
1145 if (BuildConfig.FLAVOR.contentEquals("free")) {
1146 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1147 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
1153 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1154 // Show the file chooser if the device is running API >= 21.
1155 if (Build.VERSION.SDK_INT >= 21) {
1156 // Store the file path callback.
1157 fileChooserCallback = filePathCallback;
1159 // Create an intent to open a chooser based ont the file chooser parameters.
1160 Intent fileChooserIntent = fileChooserParams.createIntent();
1162 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1163 startActivityForResult(fileChooserIntent, 0);
1169 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1170 registerForContextMenu(mainWebView);
1172 // Allow the downloading of files.
1173 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1174 // Check if the download should be processed by an external app.
1175 if (downloadWithExternalApp) { // Download with an external app.
1176 openUrlWithExternalApp(url);
1177 } else { // Download with Android's download manager.
1178 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1179 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission has not been granted.
1180 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1182 // Store the variables for future use by `onRequestPermissionsResult()`.
1184 downloadContentDisposition = contentDisposition;
1185 downloadContentLength = contentLength;
1187 // Show a dialog if the user has previously denied the permission.
1188 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1189 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1190 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1192 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1193 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1194 } else { // Show the permission request directly.
1195 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1196 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1198 } else { // The storage permission has already been granted.
1199 // Get a handle for the download file alert dialog.
1200 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1202 // Show the download file alert dialog.
1203 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1208 // Allow pinch to zoom.
1209 mainWebView.getSettings().setBuiltInZoomControls(true);
1211 // Hide zoom controls.
1212 mainWebView.getSettings().setDisplayZoomControls(false);
1214 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1215 mainWebView.getSettings().setUseWideViewPort(true);
1217 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1218 mainWebView.getSettings().setLoadWithOverviewMode(true);
1220 // Explicitly disable geolocation.
1221 mainWebView.getSettings().setGeolocationEnabled(false);
1223 // Initialize cookieManager.
1224 cookieManager = CookieManager.getInstance();
1226 // 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).
1227 customHeaders.put("X-Requested-With", "");
1229 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1230 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1232 // Get a handle for the `Runtime`.
1233 privacyBrowserRuntime = Runtime.getRuntime();
1235 // Store the application's private data directory.
1236 privateDataDirectoryString = getApplicationInfo().dataDir;
1237 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1239 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1240 inFullScreenBrowsingMode = false;
1242 // Initialize the privacy settings variables.
1243 javaScriptEnabled = false;
1244 firstPartyCookiesEnabled = false;
1245 thirdPartyCookiesEnabled = false;
1246 domStorageEnabled = false;
1247 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1250 // Store the default user agent.
1251 webViewDefaultUserAgent = mainWebView.getSettings().getUserAgentString();
1253 // Initialize the WebView title.
1254 webViewTitle = getString(R.string.no_title);
1256 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1257 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1258 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1259 assert favoriteIconBitmapDrawable != null;
1260 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1262 // If the favorite icon is null, load the default.
1263 if (favoriteIconBitmap == null) {
1264 favoriteIconBitmap = favoriteIconDefaultBitmap;
1267 // Initialize the user agent array adapter and string array.
1268 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.spinner_item);
1269 userAgentDataArray = resources.getStringArray(R.array.user_agent_data);
1271 // Apply the app settings from the shared preferences.
1274 // Instantiate the block list helper.
1275 BlockListHelper blockListHelper = new BlockListHelper();
1277 // Initialize the list of resource requests.
1278 resourceRequests = new ArrayList<>();
1280 // Parse the block lists.
1281 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1282 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1283 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1284 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1285 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1287 // Store the list versions.
1288 easyListVersion = easyList.get(0).get(0)[0];
1289 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1290 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1291 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1292 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1294 // Get a handle for the activity. This is used to update the requests counter while the navigation menu is open.
1295 Activity activity = this;
1297 mainWebView.setWebViewClient(new WebViewClient() {
1298 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1299 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1300 @SuppressWarnings("deprecation")
1302 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1303 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1304 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1305 formattedUrlString = "";
1307 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1308 boolean userAgentChanged = applyDomainSettings(url, true, false);
1310 // Check if the user agent has changed.
1311 if (userAgentChanged) {
1312 // Manually load the URL. The changing of the user agent will cause WebView to reload the previous URL.
1313 mainWebView.loadUrl(url, customHeaders);
1315 // Returning true indicates that Privacy Browser is manually handling the loading of the URL.
1318 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1321 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1322 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1323 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1325 // Parse the url and set it as the data for the intent.
1326 emailIntent.setData(Uri.parse(url));
1328 // Open the email program in a new task instead of as part of Privacy Browser.
1329 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1332 startActivity(emailIntent);
1334 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1336 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1337 // Open the dialer and load the phone number, but wait for the user to place the call.
1338 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1340 // Add the phone number to the intent.
1341 dialIntent.setData(Uri.parse(url));
1343 // Open the dialer in a new task instead of as part of Privacy Browser.
1344 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1347 startActivity(dialIntent);
1349 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1351 } else { // Load a system chooser to select an app that can handle the URL.
1352 // Open an app that can handle the URL.
1353 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1355 // Add the URL to the intent.
1356 genericIntent.setData(Uri.parse(url));
1358 // List all apps that can handle the URL instead of just opening the first one.
1359 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1361 // Open the app in a new task instead of as part of Privacy Browser.
1362 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1364 // Start the app or display a snackbar if no app is available to handle the URL.
1366 startActivity(genericIntent);
1367 } catch (ActivityNotFoundException exception) {
1368 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1371 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1376 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1377 @SuppressWarnings("deprecation")
1379 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1380 // Create an empty web resource response to be used if the resource request is blocked.
1381 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1383 // Reset the whitelist results tracker.
1384 whiteListResultStringArray = null;
1386 // Initialize the third party request tracker.
1387 boolean isThirdPartyRequest = false;
1389 // Initialize the current domain string.
1390 String currentDomain = "";
1392 // Nobody is happy when comparing null strings.
1393 if (!(formattedUrlString == null) && !(url == null)) {
1394 // Get the domain strings to URIs.
1395 Uri currentDomainUri = Uri.parse(formattedUrlString);
1396 Uri requestDomainUri = Uri.parse(url);
1398 // Get the domain host names.
1399 String currentBaseDomain = currentDomainUri.getHost();
1400 String requestBaseDomain = requestDomainUri.getHost();
1402 // Update the current domain variable.
1403 currentDomain = currentBaseDomain;
1405 // Only compare the current base domain and the request base domain if neither is null.
1406 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1407 // Determine the current base domain.
1408 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1409 // Remove the first subdomain.
1410 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1413 // Determine the request base domain.
1414 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1415 // Remove the first subdomain.
1416 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1419 // Update the third party request tracker.
1420 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1424 // Block third-party requests if enabled.
1425 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1426 // Increment the blocked requests counters.
1428 thirdPartyBlockedRequests++;
1430 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1431 activity.runOnUiThread(() -> {
1432 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1433 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1434 blockAllThirdPartyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
1437 // Add the request to the log.
1438 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1440 // Return an empty web resource response.
1441 return emptyWebResourceResponse;
1444 // Check UltraPrivacy if it is enabled.
1445 if (ultraPrivacyEnabled) {
1446 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1447 // Increment the blocked requests counters.
1449 ultraPrivacyBlockedRequests++;
1451 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1452 activity.runOnUiThread(() -> {
1453 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1454 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1455 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
1458 // The resource request was blocked. Return an empty web resource response.
1459 return emptyWebResourceResponse;
1462 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1463 if (whiteListResultStringArray != null) {
1464 // Add a whitelist entry to the resource requests array.
1465 resourceRequests.add(whiteListResultStringArray);
1467 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1472 // Check EasyList if it is enabled.
1473 if (easyListEnabled) {
1474 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1475 // Increment the blocked requests counters.
1477 easyListBlockedRequests++;
1479 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1480 activity.runOnUiThread(() -> {
1481 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1482 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1483 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
1486 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1487 whiteListResultStringArray = null;
1489 // The resource request was blocked. Return an empty web resource response.
1490 return emptyWebResourceResponse;
1494 // Check EasyPrivacy if it is enabled.
1495 if (easyPrivacyEnabled) {
1496 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1497 // Increment the blocked requests counters.
1499 easyPrivacyBlockedRequests++;
1501 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1502 activity.runOnUiThread(() -> {
1503 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1504 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1505 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
1508 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1509 whiteListResultStringArray = null;
1511 // The resource request was blocked. Return an empty web resource response.
1512 return emptyWebResourceResponse;
1516 // Check Fanboy’s Annoyance List if it is enabled.
1517 if (fanboysAnnoyanceListEnabled) {
1518 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1519 // Increment the blocked requests counters.
1521 fanboysAnnoyanceListBlockedRequests++;
1523 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1524 activity.runOnUiThread(() -> {
1525 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1526 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1527 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
1530 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1531 whiteListResultStringArray = null;
1533 // The resource request was blocked. Return an empty web resource response.
1534 return emptyWebResourceResponse;
1536 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1537 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1538 // Increment the blocked requests counters.
1540 fanboysSocialBlockingListBlockedRequests++;
1542 // Update the titles of the blocklist menu items. This must be run from the UI thread.
1543 activity.runOnUiThread(() -> {
1544 navigationRequestsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1545 blocklistsMenuItem.setTitle(getString(R.string.requests) + " - " + blockedRequests);
1546 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
1549 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1550 whiteListResultStringArray = null;
1552 // The resource request was blocked. Return an empty web resource response.
1553 return emptyWebResourceResponse;
1557 // Add the request to the log because it hasn't been processed by any of the previous checks.
1558 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1559 resourceRequests.add(whiteListResultStringArray);
1560 } else { // The request didn't match any blocklist entry. Log it as a default request.
1561 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1564 // The resource request has not been blocked. `return null` loads the requested resource.
1568 // Handle HTTP authentication requests.
1570 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1571 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1572 httpAuthHandler = handler;
1574 // Display the HTTP authentication dialog.
1575 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1576 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1579 // Update the URL in urlTextBox when the page starts to load.
1581 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1582 // Reset the list of resource requests.
1583 resourceRequests.clear();
1585 // Initialize the counters for requests blocked by each blocklist.
1586 blockedRequests = 0;
1587 easyListBlockedRequests = 0;
1588 easyPrivacyBlockedRequests = 0;
1589 fanboysAnnoyanceListBlockedRequests = 0;
1590 fanboysSocialBlockingListBlockedRequests = 0;
1591 ultraPrivacyBlockedRequests = 0;
1592 thirdPartyBlockedRequests = 0;
1594 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1596 mainWebView.setVisibility(View.INVISIBLE);
1599 // Hide the keyboard. `0` indicates no additional flags.
1600 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1602 // Check to see if Privacy Browser is waiting on Orbot.
1603 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1604 // 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.
1605 formattedUrlString = url;
1607 // Display the formatted URL text.
1608 urlTextBox.setText(formattedUrlString);
1610 // Apply text highlighting to `urlTextBox`.
1613 // Apply any custom domain settings if the URL was loaded by navigating history.
1614 if (navigatingHistory) {
1615 // Apply the domain settings.
1616 boolean userAgentChanged = applyDomainSettings(url, true, false);
1618 // Reset `navigatingHistory`.
1619 navigatingHistory = false;
1621 // Manually load the URL if the user agent has changed, which will have caused the previous URL to be reloaded.
1622 if (userAgentChanged) {
1623 loadUrl(formattedUrlString);
1627 // 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.
1628 urlIsLoading = true;
1630 // Replace Refresh with Stop if the menu item has been created. (The WebView typically begins loading before the menu items are instantiated.)
1631 if (refreshMenuItem != null) {
1633 refreshMenuItem.setTitle(R.string.stop);
1635 // If the icon is displayed in the AppBar, set it according to the theme.
1636 if (displayAdditionalAppBarIcons) {
1638 refreshMenuItem.setIcon(R.drawable.close_dark);
1640 refreshMenuItem.setIcon(R.drawable.close_light);
1647 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1649 public void onPageFinished(WebView view, String url) {
1650 // Reset the wide view port if it has been turned off by the waiting for Orbot message.
1651 if (!waitingForOrbot) {
1652 // Only use a wide view port if the URL starts with `http`, not for `file://` and `content://`.
1653 mainWebView.getSettings().setUseWideViewPort(url.startsWith("http"));
1656 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1657 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1658 cookieManager.flush();
1661 // Update the Refresh menu item if it has been created.
1662 if (refreshMenuItem != null) {
1663 // Reset the Refresh title.
1664 refreshMenuItem.setTitle(R.string.refresh);
1666 // If the icon is displayed in the AppBar, reset it according to the theme.
1667 if (displayAdditionalAppBarIcons) {
1669 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
1671 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
1676 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1677 urlIsLoading = false;
1679 // Clear the cache and history if Incognito Mode is enabled.
1680 if (incognitoModeEnabled) {
1681 // Clear the cache. `true` includes disk files.
1682 mainWebView.clearCache(true);
1684 // Clear the back/forward history.
1685 mainWebView.clearHistory();
1687 // Manually delete cache folders.
1689 // Delete the main cache directory.
1690 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1692 // Delete the secondary `Service Worker` cache directory.
1693 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1694 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1695 } catch (IOException e) {
1696 // Do nothing if an error is thrown.
1700 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1701 if (!waitingForOrbot) {
1702 // Check to see if `WebView` has set `url` to be `about:blank`.
1703 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1704 // Set `formattedUrlString` to `""`.
1705 formattedUrlString = "";
1707 urlTextBox.setText(formattedUrlString);
1709 // Request focus for `urlTextBox`.
1710 urlTextBox.requestFocus();
1712 // Display the keyboard.
1713 inputMethodManager.showSoftInput(urlTextBox, 0);
1715 // Apply the domain settings. This clears any settings from the previous domain.
1716 applyDomainSettings(formattedUrlString, true, false);
1717 } else { // `WebView` has loaded a webpage.
1718 // Set `formattedUrlString`.
1719 formattedUrlString = url;
1721 // Only update `urlTextBox` if the user is not typing in it.
1722 if (!urlTextBox.hasFocus()) {
1723 // Display the formatted URL text.
1724 urlTextBox.setText(formattedUrlString);
1726 // Apply text highlighting to `urlTextBox`.
1731 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1732 sslCertificate = mainWebView.getCertificate();
1734 // 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.
1735 // Also ignore if changes in the user agent causes an error while navigating history.
1736 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate && navigatingHistory) {
1737 // Initialize the current SSL certificate variables.
1738 String currentWebsiteIssuedToCName = "";
1739 String currentWebsiteIssuedToOName = "";
1740 String currentWebsiteIssuedToUName = "";
1741 String currentWebsiteIssuedByCName = "";
1742 String currentWebsiteIssuedByOName = "";
1743 String currentWebsiteIssuedByUName = "";
1744 Date currentWebsiteSslStartDate = null;
1745 Date currentWebsiteSslEndDate = null;
1748 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1749 if (sslCertificate != null) {
1750 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1751 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1752 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1753 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1754 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1755 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1756 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1757 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1760 // 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`.
1761 String currentWebsiteSslStartDateString = "";
1762 String currentWebsiteSslEndDateString = "";
1763 String pinnedDomainSslStartDateString = "";
1764 String pinnedDomainSslEndDateString = "";
1766 // Convert the `Dates` to `Strings` if they are not `null`.
1767 if (currentWebsiteSslStartDate != null) {
1768 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1771 if (currentWebsiteSslEndDate != null) {
1772 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1775 if (pinnedDomainSslStartDate != null) {
1776 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1779 if (pinnedDomainSslEndDate != null) {
1780 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1783 // Check to see if the pinned SSL certificate matches the current website certificate.
1784 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1785 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1786 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1787 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1788 // The pinned SSL certificate doesn't match the current domain certificate.
1789 //Display the pinned SSL certificate mismatch `AlertDialog`.
1790 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1791 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1797 // Handle SSL Certificate errors.
1799 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1800 // Get the current website SSL certificate.
1801 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1803 // Extract the individual pieces of information from the current website SSL certificate.
1804 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1805 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1806 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1807 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1808 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1809 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1810 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1811 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1813 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1814 if (pinnedDomainSslCertificate &&
1815 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1816 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1817 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1818 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1819 // An SSL certificate is pinned and matches the current domain certificate.
1820 // Proceed to the website without displaying an error.
1822 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1823 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1824 sslErrorHandler = handler;
1826 // Display the SSL error `AlertDialog`.
1827 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1828 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1833 // Get the intent that started the app.
1834 Intent launchingIntent = getIntent();
1836 // Get the information from the intent.
1837 String launchingIntentAction = launchingIntent.getAction();
1838 Uri launchingIntentUriData = launchingIntent.getData();
1840 // If the intent action is a web search, perform the search.
1841 if ((launchingIntentAction != null) && launchingIntentAction.equals(Intent.ACTION_WEB_SEARCH)) {
1842 // Create an encoded URL string.
1843 String encodedUrlString;
1845 // Sanitize the search input and convert it to a search.
1847 encodedUrlString = URLEncoder.encode(launchingIntent.getStringExtra(SearchManager.QUERY), "UTF-8");
1848 } catch (UnsupportedEncodingException exception) {
1849 encodedUrlString = "";
1852 // Add the base search URL.
1853 formattedUrlString = searchURL + encodedUrlString;
1854 } else if (launchingIntentUriData != null){ // Check to see if the intent contains a new URL.
1855 // Set the formatted URL string.
1856 formattedUrlString = launchingIntentUriData.toString();
1859 // Load the website if not waiting for Orbot to connect.
1860 if (!waitingForOrbot) {
1861 loadUrl(formattedUrlString);
1866 protected void onNewIntent(Intent intent) {
1867 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1870 // Get the information from the intent.
1871 String intentAction = intent.getAction();
1872 Uri intentUriData = intent.getData();
1874 // If the intent action is a web search, perform the search.
1875 if ((intentAction != null) && intentAction.equals(Intent.ACTION_WEB_SEARCH)) {
1876 // Create an encoded URL string.
1877 String encodedUrlString;
1879 // Sanitize the search input and convert it to a search.
1881 encodedUrlString = URLEncoder.encode(intent.getStringExtra(SearchManager.QUERY), "UTF-8");
1882 } catch (UnsupportedEncodingException exception) {
1883 encodedUrlString = "";
1886 // Add the base search URL.
1887 formattedUrlString = searchURL + encodedUrlString;
1888 } else if (intentUriData != null){ // Check to see if the intent contains a new URL.
1889 // Set the formatted URL string.
1890 formattedUrlString = intentUriData.toString();
1894 loadUrl(formattedUrlString);
1896 // Close the navigation drawer if it is open.
1897 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1898 drawerLayout.closeDrawer(GravityCompat.START);
1901 // Close the bookmarks drawer if it is open.
1902 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1903 drawerLayout.closeDrawer(GravityCompat.END);
1906 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1907 mainWebView.requestFocus();
1911 public void onRestart() {
1912 // Run the default commands.
1915 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1916 if (proxyThroughOrbot) {
1917 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1918 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1920 // Send the intent to the Orbot package.
1921 orbotIntent.setPackage("org.torproject.android");
1924 sendBroadcast(orbotIntent);
1927 // Apply the app settings if returning from the Settings activity..
1928 if (reapplyAppSettingsOnRestart) {
1929 // Apply the app settings.
1932 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1933 if (reloadOnRestart) {
1934 // Reload `mainWebView`.
1935 mainWebView.reload();
1937 // Reset `reloadOnRestartBoolean`.
1938 reloadOnRestart = false;
1941 // Reset the return from settings flag.
1942 reapplyAppSettingsOnRestart = false;
1945 // Apply the domain settings if returning from the Domains activity.
1946 if (reapplyDomainSettingsOnRestart) {
1947 // Reapply the domain settings.
1948 applyDomainSettings(formattedUrlString, false, true);
1950 // Reset `reapplyDomainSettingsOnRestart`.
1951 reapplyDomainSettingsOnRestart = false;
1954 // Load the URL on restart to apply changes to night mode.
1955 if (loadUrlOnRestart) {
1956 // Load the current `formattedUrlString`.
1957 loadUrl(formattedUrlString);
1959 // Reset `loadUrlOnRestart.
1960 loadUrlOnRestart = false;
1963 // Update the bookmarks drawer if returning from the Bookmarks activity.
1964 if (restartFromBookmarksActivity) {
1965 // Close the bookmarks drawer.
1966 drawerLayout.closeDrawer(GravityCompat.END);
1968 // Reload the bookmarks drawer.
1969 loadBookmarksFolder();
1971 // Reset `restartFromBookmarksActivity`.
1972 restartFromBookmarksActivity = false;
1975 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1976 updatePrivacyIcons(true);
1979 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1981 public void onResume() {
1982 // Run the default commands.
1985 // Resume JavaScript (if enabled).
1986 mainWebView.resumeTimers();
1988 // Resume `mainWebView`.
1989 mainWebView.onResume();
1991 // Resume the adView for the free flavor.
1992 if (BuildConfig.FLAVOR.contentEquals("free")) {
1994 AdHelper.resumeAd(findViewById(R.id.adview));
1997 // Display a message to the user if waiting for Orbot.
1998 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1999 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
2000 mainWebView.getSettings().setUseWideViewPort(false);
2002 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2003 mainWebView.loadData(waitingForOrbotHtmlString, "text/html", null);
2006 if (displayingFullScreenVideo) {
2007 // Remove the translucent overlays.
2008 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2010 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2011 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2013 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2014 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2015 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2017 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2022 public void onPause() {
2023 // Run the default commands.
2026 // Pause `mainWebView`.
2027 mainWebView.onPause();
2029 // Stop all JavaScript.
2030 mainWebView.pauseTimers();
2032 // Pause the ad or it will continue to consume resources in the background on the free flavor.
2033 if (BuildConfig.FLAVOR.contentEquals("free")) {
2035 AdHelper.pauseAd(findViewById(R.id.adview));
2040 public void onDestroy() {
2041 // Unregister the Orbot status broadcast receiver.
2042 this.unregisterReceiver(orbotStatusBroadcastReceiver);
2044 // Close the bookmarks cursor and database.
2045 bookmarksCursor.close();
2046 bookmarksDatabaseHelper.close();
2048 // Run the default commands.
2053 public boolean onCreateOptionsMenu(Menu menu) {
2054 // Inflate the menu; this adds items to the action bar if it is present.
2055 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
2057 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
2060 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
2061 updatePrivacyIcons(false);
2063 // Get handles for the menu items.
2064 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2065 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2066 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2067 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
2068 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
2069 refreshMenuItem = menu.findItem(R.id.refresh);
2070 blocklistsMenuItem = menu.findItem(R.id.blocklists);
2071 easyListMenuItem = menu.findItem(R.id.easylist);
2072 easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
2073 fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
2074 fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
2075 ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
2076 blockAllThirdPartyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
2077 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
2079 // Only display third-party cookies if API >= 21
2080 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
2082 // Only display the form data menu items if the API < 26.
2083 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
2084 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
2086 // Only show Ad Consent if this is the free flavor.
2087 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
2089 // Get the shared preference values.
2090 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2092 // Get the status of the additional AppBar icons.
2093 displayAdditionalAppBarIcons = sharedPreferences.getBoolean("display_additional_app_bar_icons", false);
2095 // 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.
2096 if (displayAdditionalAppBarIcons) {
2097 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2098 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2099 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
2100 } else { //Do not display the additional icons.
2101 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2102 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2103 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2106 // Replace Refresh with Stop if a URL is already loading.
2109 refreshMenuItem.setTitle(R.string.stop);
2111 // If the icon is displayed in the AppBar, set it according to the theme.
2112 if (displayAdditionalAppBarIcons) {
2114 refreshMenuItem.setIcon(R.drawable.close_dark);
2116 refreshMenuItem.setIcon(R.drawable.close_light);
2125 public boolean onPrepareOptionsMenu(Menu menu) {
2126 // Get handles for the menu items.
2127 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2128 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2129 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2130 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2131 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
2132 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2133 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2134 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2135 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
2136 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2137 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
2138 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2139 MenuItem nightModeMenuItem = menu.findItem(R.id.night_mode);
2140 MenuItem proxyThroughOrbotMenuItem = menu.findItem(R.id.proxy_through_orbot);
2142 // Set the text for the domain menu item.
2143 if (domainSettingsApplied) {
2144 addOrEditDomain.setTitle(R.string.edit_domain_settings);
2146 addOrEditDomain.setTitle(R.string.add_domain_settings);
2149 // Set the status of the menu item checkboxes.
2150 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2151 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2152 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2153 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
2154 easyListMenuItem.setChecked(easyListEnabled);
2155 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
2156 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
2157 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
2158 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
2159 blockAllThirdPartyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
2160 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
2161 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2162 nightModeMenuItem.setChecked(nightMode);
2163 proxyThroughOrbotMenuItem.setChecked(proxyThroughOrbot);
2165 // Enable third-party cookies if first-party cookies are enabled.
2166 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2168 // Enable DOM Storage if JavaScript is enabled.
2169 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2171 // Enable Clear Cookies if there are any.
2172 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2174 // Get a count of the number of files in the Local Storage directory.
2175 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2176 int localStorageDirectoryNumberOfFiles = 0;
2177 if (localStorageDirectory.exists()) {
2178 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2181 // Get a count of the number of files in the IndexedDB directory.
2182 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2183 int indexedDBDirectoryNumberOfFiles = 0;
2184 if (indexedDBDirectory.exists()) {
2185 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2188 // Enable Clear DOM Storage if there is any.
2189 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2191 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
2192 if (Build.VERSION.SDK_INT < 26) {
2193 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2194 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2196 // Disable clear form data because it is not supported on current version of Android.
2197 clearFormDataMenuItem.setEnabled(false);
2200 // Enable Clear Data if any of the submenu items are enabled.
2201 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2203 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
2204 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2206 // Initialize the display names for the blocklists with the number of blocked requests.
2207 blocklistsMenuItem.setTitle(getString(R.string.blocklists) + " - " + blockedRequests);
2208 easyListMenuItem.setTitle(easyListBlockedRequests + " - " + getString(R.string.easylist));
2209 easyPrivacyMenuItem.setTitle(easyPrivacyBlockedRequests + " - " + getString(R.string.easyprivacy));
2210 fanboysAnnoyanceListMenuItem.setTitle(fanboysAnnoyanceListBlockedRequests + " - " + getString(R.string.fanboys_annoyance_list));
2211 fanboysSocialBlockingListMenuItem.setTitle(fanboysSocialBlockingListBlockedRequests + " - " + getString(R.string.fanboys_social_blocking_list));
2212 ultraPrivacyMenuItem.setTitle(ultraPrivacyBlockedRequests + " - " + getString(R.string.ultraprivacy));
2213 blockAllThirdPartyRequestsMenuItem.setTitle(thirdPartyBlockedRequests + " - " + getString(R.string.block_all_third_party_requests));
2215 // Get the current user agent.
2216 String currentUserAgent = mainWebView.getSettings().getUserAgentString();
2218 // Select the current user agent menu item. A switch statement cannot be used because the user agents are not compile time constants.
2219 if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[0])) { // Privacy Browser.
2220 menu.findItem(R.id.user_agent_privacy_browser).setChecked(true);
2221 } else if (currentUserAgent.equals(webViewDefaultUserAgent)) { // WebView Default.
2222 menu.findItem(R.id.user_agent_webview_default).setChecked(true);
2223 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[2])) { // Firefox on Android.
2224 menu.findItem(R.id.user_agent_firefox_on_android).setChecked(true);
2225 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[3])) { // Chrome on Android.
2226 menu.findItem(R.id.user_agent_chrome_on_android).setChecked(true);
2227 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[4])) { // Safari on iOS.
2228 menu.findItem(R.id.user_agent_safari_on_ios).setChecked(true);
2229 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[5])) { // Firefox on Linux.
2230 menu.findItem(R.id.user_agent_firefox_on_linux).setChecked(true);
2231 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[6])) { // Chromium on Linux.
2232 menu.findItem(R.id.user_agent_chromium_on_linux).setChecked(true);
2233 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[7])) { // Firefox on Windows.
2234 menu.findItem(R.id.user_agent_firefox_on_windows).setChecked(true);
2235 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[8])) { // Chrome on Windows.
2236 menu.findItem(R.id.user_agent_chrome_on_windows).setChecked(true);
2237 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[9])) { // Edge on Windows.
2238 menu.findItem(R.id.user_agent_edge_on_windows).setChecked(true);
2239 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[10])) { // Internet Explorer on Windows.
2240 menu.findItem(R.id.user_agent_internet_explorer_on_windows).setChecked(true);
2241 } else if (currentUserAgent.equals(getResources().getStringArray(R.array.user_agent_data)[11])) { // Safari on macOS.
2242 menu.findItem(R.id.user_agent_safari_on_macos).setChecked(true);
2243 } else { // Custom user agent.
2244 menu.findItem(R.id.user_agent_custom).setChecked(true);
2247 // Initialize font size variables.
2248 int fontSize = mainWebView.getSettings().getTextZoom();
2249 String fontSizeTitle;
2250 MenuItem selectedFontSizeMenuItem;
2252 // Prepare the font size title and current size menu item.
2255 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2256 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2260 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2261 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2265 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2266 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2270 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2271 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2275 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2276 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2280 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2281 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2285 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2286 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2290 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2291 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2295 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2296 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2300 // Set the font size title and select the current size menu item.
2301 fontSizeMenuItem.setTitle(fontSizeTitle);
2302 selectedFontSizeMenuItem.setChecked(true);
2304 // Run all the other default commands.
2305 super.onPrepareOptionsMenu(menu);
2307 // Display the menu.
2312 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2313 @SuppressLint("SetJavaScriptEnabled")
2314 // removeAllCookies is deprecated, but it is required for API < 21.
2315 @SuppressWarnings("deprecation")
2316 public boolean onOptionsItemSelected(MenuItem menuItem) {
2317 // Get the selected menu item ID.
2318 int menuItemId = menuItem.getItemId();
2320 // Set the commands that relate to the menu entries.
2321 switch (menuItemId) {
2322 case R.id.toggle_javascript:
2323 // Switch the status of javaScriptEnabled.
2324 javaScriptEnabled = !javaScriptEnabled;
2326 // Apply the new JavaScript status.
2327 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2329 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2330 updatePrivacyIcons(true);
2332 // Display a `Snackbar`.
2333 if (javaScriptEnabled) { // JavaScrip is enabled.
2334 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2335 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2336 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2337 } else { // Privacy mode.
2338 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2341 // Reload the WebView.
2342 mainWebView.reload();
2345 case R.id.add_or_edit_domain:
2346 if (domainSettingsApplied) { // Edit the current domain settings.
2347 // Reapply the domain settings on returning to `MainWebViewActivity`.
2348 reapplyDomainSettingsOnRestart = true;
2349 currentDomainName = "";
2351 // Create an intent to launch the domains activity.
2352 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2354 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2355 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2356 domainsIntent.putExtra("closeOnBack", true);
2359 startActivity(domainsIntent);
2360 } else { // Add a new domain.
2361 // Apply the new domain settings on returning to `MainWebViewActivity`.
2362 reapplyDomainSettingsOnRestart = true;
2363 currentDomainName = "";
2365 // Get the current domain
2366 Uri currentUri = Uri.parse(formattedUrlString);
2367 String currentDomain = currentUri.getHost();
2369 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2370 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2372 // Create the domain and store the database ID.
2373 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2375 // Create an intent to launch the domains activity.
2376 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2378 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2379 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2380 domainsIntent.putExtra("closeOnBack", true);
2383 startActivity(domainsIntent);
2387 case R.id.toggle_first_party_cookies:
2388 // Switch the status of firstPartyCookiesEnabled.
2389 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2391 // Update the menu checkbox.
2392 menuItem.setChecked(firstPartyCookiesEnabled);
2394 // Apply the new cookie status.
2395 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2397 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2398 updatePrivacyIcons(true);
2400 // Display a `Snackbar`.
2401 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2402 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2403 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2404 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2405 } else { // Privacy mode.
2406 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2409 // Reload the WebView.
2410 mainWebView.reload();
2413 case R.id.toggle_third_party_cookies:
2414 if (Build.VERSION.SDK_INT >= 21) {
2415 // Switch the status of thirdPartyCookiesEnabled.
2416 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2418 // Update the menu checkbox.
2419 menuItem.setChecked(thirdPartyCookiesEnabled);
2421 // Apply the new cookie status.
2422 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2424 // Display a `Snackbar`.
2425 if (thirdPartyCookiesEnabled) {
2426 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2428 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2431 // Reload the WebView.
2432 mainWebView.reload();
2433 } // Else do nothing because SDK < 21.
2436 case R.id.toggle_dom_storage:
2437 // Switch the status of domStorageEnabled.
2438 domStorageEnabled = !domStorageEnabled;
2440 // Update the menu checkbox.
2441 menuItem.setChecked(domStorageEnabled);
2443 // Apply the new DOM Storage status.
2444 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2446 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2447 updatePrivacyIcons(true);
2449 // Display a `Snackbar`.
2450 if (domStorageEnabled) {
2451 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2453 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2456 // Reload the WebView.
2457 mainWebView.reload();
2460 // Form data can be removed once the minimum API >= 26.
2461 case R.id.toggle_save_form_data:
2462 // Switch the status of saveFormDataEnabled.
2463 saveFormDataEnabled = !saveFormDataEnabled;
2465 // Update the menu checkbox.
2466 menuItem.setChecked(saveFormDataEnabled);
2468 // Apply the new form data status.
2469 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2471 // Display a `Snackbar`.
2472 if (saveFormDataEnabled) {
2473 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2475 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2478 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2479 updatePrivacyIcons(true);
2481 // Reload the WebView.
2482 mainWebView.reload();
2485 case R.id.clear_cookies:
2486 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2487 .setAction(R.string.undo, v -> {
2488 // Do nothing because everything will be handled by `onDismissed()` below.
2490 .addCallback(new Snackbar.Callback() {
2492 public void onDismissed(Snackbar snackbar, int event) {
2494 // The user pushed the `Undo` button.
2495 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2499 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2501 // `cookieManager.removeAllCookie()` varies by SDK.
2502 if (Build.VERSION.SDK_INT < 21) {
2503 cookieManager.removeAllCookie();
2505 // `null` indicates no callback.
2506 cookieManager.removeAllCookies(null);
2514 case R.id.clear_dom_storage:
2515 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2516 .setAction(R.string.undo, v -> {
2517 // Do nothing because everything will be handled by `onDismissed()` below.
2519 .addCallback(new Snackbar.Callback() {
2521 public void onDismissed(Snackbar snackbar, int event) {
2523 // The user pushed the `Undo` button.
2524 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2528 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2530 // Delete the DOM Storage.
2531 WebStorage webStorage = WebStorage.getInstance();
2532 webStorage.deleteAllData();
2534 // Initialize a handler to manually delete the DOM storage files and directories.
2535 Handler deleteDomStorageHandler = new Handler();
2537 // Setup a runnable to manually delete the DOM storage files and directories.
2538 Runnable deleteDomStorageRunnable = () -> {
2540 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2541 privacyBrowserRuntime.exec(new String[]{"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2543 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2544 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2545 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2546 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2547 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2548 } catch (IOException e) {
2549 // Do nothing if an error is thrown.
2553 // Manually delete the DOM storage files after 200 milliseconds.
2554 deleteDomStorageHandler.postDelayed(deleteDomStorageRunnable, 200);
2561 // Form data can be remove once the minimum API >= 26.
2562 case R.id.clear_form_data:
2563 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2564 .setAction(R.string.undo, v -> {
2565 // Do nothing because everything will be handled by `onDismissed()` below.
2567 .addCallback(new Snackbar.Callback() {
2569 public void onDismissed(Snackbar snackbar, int event) {
2571 // The user pushed the `Undo` button.
2572 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2576 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2578 // Delete the form data.
2579 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2580 mainWebViewDatabase.clearFormData();
2588 // Toggle the EasyList status.
2589 easyListEnabled = !easyListEnabled;
2591 // Update the menu checkbox.
2592 menuItem.setChecked(easyListEnabled);
2594 // Reload the main WebView.
2595 mainWebView.reload();
2598 case R.id.easyprivacy:
2599 // Toggle the EasyPrivacy status.
2600 easyPrivacyEnabled = !easyPrivacyEnabled;
2602 // Update the menu checkbox.
2603 menuItem.setChecked(easyPrivacyEnabled);
2605 // Reload the main WebView.
2606 mainWebView.reload();
2609 case R.id.fanboys_annoyance_list:
2610 // Toggle Fanboy's Annoyance List status.
2611 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2613 // Update the menu checkbox.
2614 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2616 // Update the staus of Fanboy's Social Blocking List.
2617 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2618 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2620 // Reload the main WebView.
2621 mainWebView.reload();
2624 case R.id.fanboys_social_blocking_list:
2625 // Toggle Fanboy's Social Blocking List status.
2626 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2628 // Update the menu checkbox.
2629 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2631 // Reload the main WebView.
2632 mainWebView.reload();
2635 case R.id.ultraprivacy:
2636 // Toggle the UltraPrivacy status.
2637 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2639 // Update the menu checkbox.
2640 menuItem.setChecked(ultraPrivacyEnabled);
2642 // Reload the main WebView.
2643 mainWebView.reload();
2646 case R.id.block_all_third_party_requests:
2647 //Toggle the third-party requests blocker status.
2648 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2650 // Update the menu checkbox.
2651 menuItem.setChecked(blockAllThirdPartyRequests);
2653 // Reload the main WebView.
2654 mainWebView.reload();
2657 case R.id.user_agent_privacy_browser:
2658 // Update the user agent.
2659 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[0]);
2661 // Reload the WebView.
2662 mainWebView.reload();
2665 case R.id.user_agent_webview_default:
2666 // Update the user agent.
2667 mainWebView.getSettings().setUserAgentString("");
2669 // Reload the WebView.
2670 mainWebView.reload();
2673 case R.id.user_agent_firefox_on_android:
2674 // Update the user agent.
2675 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[2]);
2677 // Reload the WebView.
2678 mainWebView.reload();
2681 case R.id.user_agent_chrome_on_android:
2682 // Update the user agent.
2683 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[3]);
2685 // Reload the WebView.
2686 mainWebView.reload();
2689 case R.id.user_agent_safari_on_ios:
2690 // Update the user agent.
2691 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[4]);
2693 // Reload the WebView.
2694 mainWebView.reload();
2697 case R.id.user_agent_firefox_on_linux:
2698 // Update the user agent.
2699 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[5]);
2701 // Reload the WebView.
2702 mainWebView.reload();
2705 case R.id.user_agent_chromium_on_linux:
2706 // Update the user agent.
2707 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[6]);
2709 // Reload the WebView.
2710 mainWebView.reload();
2713 case R.id.user_agent_firefox_on_windows:
2714 // Update the user agent.
2715 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[7]);
2717 // Reload the WebView.
2718 mainWebView.reload();
2721 case R.id.user_agent_chrome_on_windows:
2722 // Update the user agent.
2723 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[8]);
2725 // Reload the WebView.
2726 mainWebView.reload();
2729 case R.id.user_agent_edge_on_windows:
2730 // Update the user agent.
2731 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[9]);
2733 // Reload the WebView.
2734 mainWebView.reload();
2737 case R.id.user_agent_internet_explorer_on_windows:
2738 // Update the user agent.
2739 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[10]);
2741 // Reload the WebView.
2742 mainWebView.reload();
2745 case R.id.user_agent_safari_on_macos:
2746 // Update the user agent.
2747 mainWebView.getSettings().setUserAgentString(getResources().getStringArray(R.array.user_agent_data)[11]);
2749 // Reload the WebView.
2750 mainWebView.reload();
2753 case R.id.user_agent_custom:
2754 // Update the user agent.
2755 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2757 // Reload the WebView.
2758 mainWebView.reload();
2761 case R.id.font_size_twenty_five_percent:
2762 mainWebView.getSettings().setTextZoom(25);
2765 case R.id.font_size_fifty_percent:
2766 mainWebView.getSettings().setTextZoom(50);
2769 case R.id.font_size_seventy_five_percent:
2770 mainWebView.getSettings().setTextZoom(75);
2773 case R.id.font_size_one_hundred_percent:
2774 mainWebView.getSettings().setTextZoom(100);
2777 case R.id.font_size_one_hundred_twenty_five_percent:
2778 mainWebView.getSettings().setTextZoom(125);
2781 case R.id.font_size_one_hundred_fifty_percent:
2782 mainWebView.getSettings().setTextZoom(150);
2785 case R.id.font_size_one_hundred_seventy_five_percent:
2786 mainWebView.getSettings().setTextZoom(175);
2789 case R.id.font_size_two_hundred_percent:
2790 mainWebView.getSettings().setTextZoom(200);
2793 case R.id.swipe_to_refresh:
2794 // Toggle swipe to refresh.
2795 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2798 case R.id.display_images:
2799 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2800 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2801 mainWebView.reload();
2802 } else { // Images are not currently loaded automatically.
2803 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2807 case R.id.night_mode:
2808 // Toggle night mode.
2809 nightMode = !nightMode;
2811 // Enable or disable JavaScript according to night mode, the global preference, and any domain settings.
2812 if (nightMode) { // Night mode is enabled. Enable JavaScript.
2813 // Update the global variable.
2814 javaScriptEnabled = true;
2815 } else if (domainSettingsApplied) { // Night mode is disabled and domain settings are applied. Set JavaScript according to the domain settings.
2816 // Get the JavaScript preference that was stored the last time domain settings were loaded.
2817 javaScriptEnabled = domainSettingsJavaScriptEnabled;
2818 } else { // Night mode is disabled and domain settings are not applied. Set JavaScript according to the global preference.
2819 // Get a handle for the shared preference.
2820 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2822 // Get the JavaScript preference.
2823 javaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
2826 // Apply the JavaScript setting to the WebView.
2827 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2829 // Update the privacy icons.
2830 updatePrivacyIcons(false);
2832 // Reload the website.
2833 mainWebView.reload();
2837 // Get a `PrintManager` instance.
2838 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2840 // Convert `mainWebView` to `printDocumentAdapter`.
2841 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2843 // Remove the lint error below that `printManager` might be `null`.
2844 assert printManager != null;
2846 // Print the document. The print attributes are `null`.
2847 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2850 case R.id.view_source:
2851 // Launch the View Source activity.
2852 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2853 startActivity(viewSourceIntent);
2856 case R.id.proxy_through_orbot:
2857 // Toggle the proxy through Orbot variable.
2858 proxyThroughOrbot = !proxyThroughOrbot;
2860 // Apply the proxy through Orbot settings.
2861 applyProxyThroughOrbot(true);
2865 // Setup the share string.
2866 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2868 // Create the share intent.
2869 Intent shareIntent = new Intent(Intent.ACTION_SEND);
2870 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2871 shareIntent.setType("text/plain");
2874 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2877 case R.id.find_on_page:
2878 // Hide the URL app bar.
2879 supportAppBar.setVisibility(View.GONE);
2881 // Show the Find on Page `RelativeLayout`.
2882 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2884 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2885 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2886 findOnPageEditText.postDelayed(() -> {
2887 // Set the focus on `findOnPageEditText`.
2888 findOnPageEditText.requestFocus();
2890 // Display the keyboard. `0` sets no input flags.
2891 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2895 case R.id.add_to_homescreen:
2896 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2897 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2898 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2900 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2904 if (menuItem.getTitle().equals(getString(R.string.refresh))) { // The refresh button was pushed.
2905 // Reload the WebView.
2906 mainWebView.reload();
2907 } else { // The stop button was pushed.
2908 // Stop the loading of the WebView.
2909 mainWebView.stopLoading();
2913 case R.id.ad_consent:
2914 // Display the ad consent dialog.
2915 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2916 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2920 // Don't consume the event.
2921 return super.onOptionsItemSelected(menuItem);
2925 // removeAllCookies is deprecated, but it is required for API < 21.
2926 @SuppressWarnings("deprecation")
2928 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2929 int menuItemId = menuItem.getItemId();
2931 switch (menuItemId) {
2937 if (mainWebView.canGoBack()) {
2938 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2939 formattedUrlString = "";
2941 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2942 navigatingHistory = true;
2944 // Load the previous website in the history.
2945 mainWebView.goBack();
2950 if (mainWebView.canGoForward()) {
2951 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2952 formattedUrlString = "";
2954 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2955 navigatingHistory = true;
2957 // Load the next website in the history.
2958 mainWebView.goForward();
2963 // Get the `WebBackForwardList`.
2964 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2966 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2967 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2968 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2972 // Launch the requests activity.
2973 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2974 startActivity(requestsIntent);
2977 case R.id.downloads:
2978 // Launch the system Download Manager.
2979 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2981 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2982 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2984 startActivity(downloadManagerIntent);
2988 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2989 reapplyDomainSettingsOnRestart = true;
2990 currentDomainName = "";
2992 // Launch the domains activity.
2993 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2994 startActivity(domainsIntent);
2998 // Set the flag to reapply app settings on restart when returning from Settings.
2999 reapplyAppSettingsOnRestart = true;
3001 // Set the flag to reapply the domain settings on restart when returning from Settings.
3002 reapplyDomainSettingsOnRestart = true;
3003 currentDomainName = "";
3005 // Launch the settings activity.
3006 Intent settingsIntent = new Intent(this, SettingsActivity.class);
3007 startActivity(settingsIntent);
3010 case R.id.import_export:
3011 // Launch the import/export activity.
3012 Intent importExportIntent = new Intent (this, ImportExportActivity.class);
3013 startActivity(importExportIntent);
3017 // Launch `GuideActivity`.
3018 Intent guideIntent = new Intent(this, GuideActivity.class);
3019 startActivity(guideIntent);
3023 // Launch `AboutActivity`.
3024 Intent aboutIntent = new Intent(this, AboutActivity.class);
3025 startActivity(aboutIntent);
3028 case R.id.clearAndExit:
3029 // Close the bookmarks cursor and database.
3030 bookmarksCursor.close();
3031 bookmarksDatabaseHelper.close();
3033 // Get a handle for `sharedPreferences`. `this` references the current context.
3034 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3036 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
3039 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
3040 // The command to remove cookies changed slightly in API 21.
3041 if (Build.VERSION.SDK_INT >= 21) {
3042 cookieManager.removeAllCookies(null);
3044 cookieManager.removeAllCookie();
3047 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
3049 // We have to use two commands because `Runtime.exec()` does not like `*`.
3050 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
3051 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
3052 } catch (IOException e) {
3053 // Do nothing if an error is thrown.
3057 // Clear DOM storage.
3058 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
3059 // Ask `WebStorage` to clear the DOM storage.
3060 WebStorage webStorage = WebStorage.getInstance();
3061 webStorage.deleteAllData();
3063 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
3065 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
3066 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
3068 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
3069 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
3070 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
3071 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
3072 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
3073 } catch (IOException e) {
3074 // Do nothing if an error is thrown.
3078 // Clear form data if the API < 26.
3079 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
3080 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
3081 webViewDatabase.clearFormData();
3083 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
3085 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
3086 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
3087 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
3088 } catch (IOException e) {
3089 // Do nothing if an error is thrown.
3094 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
3095 // `true` includes disk files.
3096 mainWebView.clearCache(true);
3098 // Manually delete the cache directories.
3100 // Delete the main cache directory.
3101 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
3103 // Delete the secondary `Service Worker` cache directory.
3104 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
3105 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
3106 } catch (IOException e) {
3107 // Do nothing if an error is thrown.
3111 // Clear SSL certificate preferences.
3112 mainWebView.clearSslPreferences();
3114 // Clear the back/forward history.
3115 mainWebView.clearHistory();
3117 // Clear `formattedUrlString`.
3118 formattedUrlString = null;
3120 // Clear `customHeaders`.
3121 customHeaders.clear();
3123 // Detach all views from `mainWebViewRelativeLayout`.
3124 mainWebViewRelativeLayout.removeAllViews();
3126 // Destroy the internal state of `mainWebView`.
3127 mainWebView.destroy();
3129 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
3130 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
3131 if (clearEverything) {
3133 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
3134 } catch (IOException e) {
3135 // Do nothing if an error is thrown.
3139 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
3140 if (Build.VERSION.SDK_INT >= 21) {
3141 finishAndRemoveTask();
3146 // Remove the terminated program from RAM. The status code is `0`.
3151 // Close the navigation drawer.
3152 drawerLayout.closeDrawer(GravityCompat.START);
3157 public void onPostCreate(Bundle savedInstanceState) {
3158 super.onPostCreate(savedInstanceState);
3160 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
3161 drawerToggle.syncState();
3165 public void onConfigurationChanged(Configuration newConfig) {
3166 super.onConfigurationChanged(newConfig);
3168 // Reload the ad for the free flavor if we not in full screen mode.
3169 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
3170 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3171 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_unit_id));
3174 // `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:
3175 // https://code.google.com/p/android/issues/detail?id=20493#c8
3176 // ActivityCompat.invalidateOptionsMenu(this);
3180 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
3181 // Store the `HitTestResult`.
3182 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
3185 final String imageUrl;
3186 final String linkUrl;
3188 // Get a handle for the `ClipboardManager`.
3189 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
3191 // Remove the lint errors below that `clipboardManager` might be `null`.
3192 assert clipboardManager != null;
3194 switch (hitTestResult.getType()) {
3195 // `SRC_ANCHOR_TYPE` is a link.
3196 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
3197 // Get the target URL.
3198 linkUrl = hitTestResult.getExtra();
3200 // Set the target URL as the title of the `ContextMenu`.
3201 menu.setHeaderTitle(linkUrl);
3203 // Add a Load URL entry.
3204 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
3209 // Add a Copy URL entry.
3210 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
3211 // Save the link URL in a `ClipData`.
3212 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
3214 // Set the `ClipData` as the clipboard's primary clip.
3215 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
3219 // Add a Download URL entry.
3220 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
3221 // Check if the download should be processed by an external app.
3222 if (downloadWithExternalApp) { // Download with an external app.
3223 openUrlWithExternalApp(linkUrl);
3224 } else { // Download with Android's download manager.
3225 // Check to see if the storage permission has already been granted.
3226 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
3227 // Store the variables for future use by `onRequestPermissionsResult()`.
3228 downloadUrl = linkUrl;
3229 downloadContentDisposition = "none";
3230 downloadContentLength = -1;
3232 // Show a dialog if the user has previously denied the permission.
3233 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3234 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
3235 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
3237 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
3238 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3239 } else { // Show the permission request directly.
3240 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
3241 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3243 } else { // The storage permission has already been granted.
3244 // Get a handle for the download file alert dialog.
3245 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
3247 // Show the download file alert dialog.
3248 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3254 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3255 menu.add(R.string.cancel);
3258 case WebView.HitTestResult.EMAIL_TYPE:
3259 // Get the target URL.
3260 linkUrl = hitTestResult.getExtra();
3262 // Set the target URL as the title of the `ContextMenu`.
3263 menu.setHeaderTitle(linkUrl);
3265 // Add a `Write Email` entry.
3266 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
3267 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
3268 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
3270 // Parse the url and set it as the data for the `Intent`.
3271 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
3273 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
3274 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3277 startActivity(emailIntent);
3281 // Add a `Copy Email Address` entry.
3282 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
3283 // Save the email address in a `ClipData`.
3284 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
3286 // Set the `ClipData` as the clipboard's primary clip.
3287 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
3291 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3292 menu.add(R.string.cancel);
3295 // `IMAGE_TYPE` is an image.
3296 case WebView.HitTestResult.IMAGE_TYPE:
3297 // Get the image URL.
3298 imageUrl = hitTestResult.getExtra();
3300 // Set the image URL as the title of the `ContextMenu`.
3301 menu.setHeaderTitle(imageUrl);
3303 // Add a `View Image` entry.
3304 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3309 // Add a `Download Image` entry.
3310 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3311 // Check if the download should be processed by an external app.
3312 if (downloadWithExternalApp) { // Download with an external app.
3313 openUrlWithExternalApp(imageUrl);
3314 } else { // Download with Android's download manager.
3315 // Check to see if the storage permission has already been granted.
3316 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
3317 // Store the image URL for use by `onRequestPermissionResult()`.
3318 downloadImageUrl = imageUrl;
3320 // Show a dialog if the user has previously denied the permission.
3321 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3322 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3323 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3325 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3326 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3327 } else { // Show the permission request directly.
3328 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3329 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3331 } else { // The storage permission has already been granted.
3332 // Get a handle for the download image alert dialog.
3333 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3335 // Show the download image alert dialog.
3336 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3342 // Add a `Copy URL` entry.
3343 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3344 // Save the image URL in a `ClipData`.
3345 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3347 // Set the `ClipData` as the clipboard's primary clip.
3348 clipboardManager.setPrimaryClip(srcImageTypeClipData);
3352 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3353 menu.add(R.string.cancel);
3357 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
3358 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
3359 // Get the image URL.
3360 imageUrl = hitTestResult.getExtra();
3362 // Set the image URL as the title of the `ContextMenu`.
3363 menu.setHeaderTitle(imageUrl);
3365 // Add a `View Image` entry.
3366 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3371 // Add a `Download Image` entry.
3372 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3373 // Check if the download should be processed by an external app.
3374 if (downloadWithExternalApp) { // Download with an external app.
3375 openUrlWithExternalApp(imageUrl);
3376 } else { // Download with Android's download manager.
3377 // Check to see if the storage permission has already been granted.
3378 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { // The storage permission needs to be requested.
3379 // Store the image URL for use by `onRequestPermissionResult()`.
3380 downloadImageUrl = imageUrl;
3382 // Show a dialog if the user has previously denied the permission.
3383 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
3384 // Instantiate the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
3385 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
3387 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
3388 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
3389 } else { // Show the permission request directly.
3390 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
3391 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3393 } else { // The storage permission has already been granted.
3394 // Get a handle for the download image alert dialog.
3395 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3397 // Show the download image alert dialog.
3398 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3404 // Add a `Copy URL` entry.
3405 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3406 // Save the image URL in a `ClipData`.
3407 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3409 // Set the `ClipData` as the clipboard's primary clip.
3410 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3414 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3415 menu.add(R.string.cancel);
3421 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3422 // Get the `EditTexts` from the `dialogFragment`.
3423 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3424 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3426 // Extract the strings from the `EditTexts`.
3427 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3428 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3430 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3431 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3432 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3433 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3435 // Display the new bookmark below the current items in the (0 indexed) list.
3436 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3438 // Create the bookmark.
3439 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3441 // Update `bookmarksCursor` with the current contents of this folder.
3442 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3444 // Update the `ListView`.
3445 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3447 // Scroll to the new bookmark.
3448 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3452 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3453 // Get handles for the views in `dialogFragment`.
3454 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3455 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3456 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3458 // Get new folder name string.
3459 String folderNameString = createFolderNameEditText.getText().toString();
3461 // Get the new folder icon `Bitmap`.
3462 Bitmap folderIconBitmap;
3463 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3464 // Get the default folder icon and convert it to a `Bitmap`.
3465 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3466 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3467 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3468 } else { // Use the `WebView` favorite icon.
3469 folderIconBitmap = favoriteIconBitmap;
3472 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3473 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3474 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3475 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3477 // Move all the bookmarks down one in the display order.
3478 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3479 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3480 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3483 // Create the folder, which will be placed at the top of the `ListView`.
3484 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3486 // Update `bookmarksCursor` with the current contents of this folder.
3487 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3489 // Update the `ListView`.
3490 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3492 // Scroll to the new folder.
3493 bookmarksListView.setSelection(0);
3497 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3498 // Get the shortcut name.
3499 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3500 String shortcutNameString = shortcutNameEditText.getText().toString();
3502 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3503 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3505 // Setup the shortcut intent.
3506 Intent shortcutIntent = new Intent(Intent.ACTION_VIEW);
3507 shortcutIntent.setData(Uri.parse(formattedUrlString));
3509 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3510 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3512 // Add the required fields to the shortcut info builder.
3513 shortcutInfoBuilder.setIcon(favoriteIcon);
3514 shortcutInfoBuilder.setIntent(shortcutIntent);
3515 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3517 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3518 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3522 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3523 switch (downloadType) {
3524 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3525 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3526 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3529 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3530 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3531 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3537 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
3538 switch (requestCode) {
3539 case DOWNLOAD_FILE_REQUEST_CODE:
3540 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3541 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3543 // On API 23, displaying the fragment must be delayed or the app will crash.
3544 if (Build.VERSION.SDK_INT == 23) {
3545 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3547 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3550 // Reset the download variables.
3552 downloadContentDisposition = "";
3553 downloadContentLength = 0;
3556 case DOWNLOAD_IMAGE_REQUEST_CODE:
3557 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3558 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3560 // On API 23, displaying the fragment must be delayed or the app will crash.
3561 if (Build.VERSION.SDK_INT == 23) {
3562 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3564 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3567 // Reset the image URL variable.
3568 downloadImageUrl = "";
3574 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3575 // Download the image if it has an HTTP or HTTPS URI.
3576 if (imageUrl.startsWith("http")) {
3577 // Get a handle for the system `DOWNLOAD_SERVICE`.
3578 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3580 // Parse `imageUrl`.
3581 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3583 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3584 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3585 if (firstPartyCookiesEnabled) {
3586 // Get the cookies for `imageUrl`.
3587 String cookies = cookieManager.getCookie(imageUrl);
3589 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3590 downloadRequest.addRequestHeader("Cookie", cookies);
3593 // Get the file name from the dialog fragment.
3594 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3595 String imageName = downloadImageNameEditText.getText().toString();
3597 // Specify the download location.
3598 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3599 // Download to the public download directory.
3600 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3601 } else { // External write permission denied.
3602 // Download to the app's external download directory.
3603 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3606 // Allow `MediaScanner` to index the download if it is a media file.
3607 downloadRequest.allowScanningByMediaScanner();
3609 // Add the URL as the description for the download.
3610 downloadRequest.setDescription(imageUrl);
3612 // Show the download notification after the download is completed.
3613 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3615 // Remove the lint warning below that `downloadManager` might be `null`.
3616 assert downloadManager != null;
3618 // Initiate the download.
3619 downloadManager.enqueue(downloadRequest);
3620 } else { // The image is not an HTTP or HTTPS URI.
3621 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3626 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3627 // Download the file if it has an HTTP or HTTPS URI.
3628 if (downloadUrl.startsWith("http")) {
3629 // Get a handle for the system `DOWNLOAD_SERVICE`.
3630 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3632 // Parse `downloadUrl`.
3633 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3635 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3636 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3637 if (firstPartyCookiesEnabled) {
3638 // Get the cookies for `downloadUrl`.
3639 String cookies = cookieManager.getCookie(downloadUrl);
3641 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3642 downloadRequest.addRequestHeader("Cookie", cookies);
3645 // Get the file name from the dialog fragment.
3646 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3647 String fileName = downloadFileNameEditText.getText().toString();
3649 // Specify the download location.
3650 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3651 // Download to the public download directory.
3652 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3653 } else { // External write permission denied.
3654 // Download to the app's external download directory.
3655 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3658 // Allow `MediaScanner` to index the download if it is a media file.
3659 downloadRequest.allowScanningByMediaScanner();
3661 // Add the URL as the description for the download.
3662 downloadRequest.setDescription(downloadUrl);
3664 // Show the download notification after the download is completed.
3665 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3667 // Remove the lint warning below that `downloadManager` might be `null`.
3668 assert downloadManager != null;
3670 // Initiate the download.
3671 downloadManager.enqueue(downloadRequest);
3672 } else { // The download is not an HTTP or HTTPS URI.
3673 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3678 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3679 // Get handles for the views from `dialogFragment`.
3680 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3681 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3682 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3684 // Store the bookmark strings.
3685 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3686 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3688 // Update the bookmark.
3689 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3690 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3691 } else { // Update the bookmark using the `WebView` favorite icon.
3692 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3693 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3694 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3695 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3697 // Update the bookmark and the favorite icon.
3698 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3701 // Update `bookmarksCursor` with the current contents of this folder.
3702 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3704 // Update the `ListView`.
3705 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3709 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3710 // Get handles for the views from `dialogFragment`.
3711 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3712 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3713 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3714 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3716 // Get the new folder name.
3717 String newFolderNameString = editFolderNameEditText.getText().toString();
3719 // Check if the favorite icon has changed.
3720 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3721 // Update the name in the database.
3722 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3723 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3724 // Get the new folder icon `Bitmap`.
3725 Bitmap folderIconBitmap;
3726 if (defaultFolderIconRadioButton.isChecked()) {
3727 // Get the default folder icon and convert it to a `Bitmap`.
3728 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3729 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3730 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3731 } else { // Use the `WebView` favorite icon.
3732 folderIconBitmap = favoriteIconBitmap;
3735 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3736 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3737 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3738 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3740 // Update the folder icon in the database.
3741 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3742 } else { // The folder icon and the name have changed.
3743 // Get the new folder icon `Bitmap`.
3744 Bitmap folderIconBitmap;
3745 if (defaultFolderIconRadioButton.isChecked()) {
3746 // Get the default folder icon and convert it to a `Bitmap`.
3747 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3748 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3749 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3750 } else { // Use the `WebView` favorite icon.
3751 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3754 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3755 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3756 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3757 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3759 // Update the folder name and icon in the database.
3760 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3763 // Update `bookmarksCursor` with the current contents of this folder.
3764 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3766 // Update the `ListView`.
3767 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3771 public void onHttpAuthenticationCancel() {
3772 // Cancel the `HttpAuthHandler`.
3773 httpAuthHandler.cancel();
3777 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3778 // Get handles for the `EditTexts`.
3779 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3780 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3782 // Proceed with the HTTP authentication.
3783 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3786 public void viewSslCertificate(View view) {
3787 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3788 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3789 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3793 public void onSslErrorCancel() {
3794 sslErrorHandler.cancel();
3798 public void onSslErrorProceed() {
3799 sslErrorHandler.proceed();
3803 public void onSslMismatchBack() {
3804 if (mainWebView.canGoBack()) { // There is a back page in the history.
3805 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3806 formattedUrlString = "";
3808 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3809 navigatingHistory = true;
3812 mainWebView.goBack();
3813 } else { // There are no pages to go back to.
3814 // Load a blank page
3820 public void onSslMismatchProceed() {
3821 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3822 ignorePinnedSslCertificate = true;
3826 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3827 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3828 formattedUrlString = "";
3830 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3831 navigatingHistory = true;
3833 // Load the history entry.
3834 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3838 public void onClearHistory() {
3839 // Clear the history.
3840 mainWebView.clearHistory();
3843 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3845 public void onBackPressed() {
3846 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3847 // Close the navigation drawer.
3848 drawerLayout.closeDrawer(GravityCompat.START);
3849 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3850 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3851 // close the bookmarks drawer.
3852 drawerLayout.closeDrawer(GravityCompat.END);
3853 } else { // A subfolder is displayed.
3854 // Place the former parent folder in `currentFolder`.
3855 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3857 // Load the new folder.
3858 loadBookmarksFolder();
3861 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3862 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3863 formattedUrlString = "";
3865 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3866 navigatingHistory = true;
3869 mainWebView.goBack();
3870 } else { // There isn't anything to do in Privacy Browser.
3871 // Pass `onBackPressed()` to the system.
3872 super.onBackPressed();
3876 // 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.
3878 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3879 // File uploads only work on API >= 21.
3880 if (Build.VERSION.SDK_INT >= 21) {
3881 // Pass the file to the WebView.
3882 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3886 private void loadUrlFromTextBox() {
3887 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3888 String unformattedUrlString = urlTextBox.getText().toString().trim();
3890 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3891 if (unformattedUrlString.startsWith("content://")) {
3892 // Load the entire content URL.
3893 formattedUrlString = unformattedUrlString;
3894 } else if (Patterns.WEB_URL.matcher(unformattedUrlString).matches() || unformattedUrlString.startsWith("http://") || unformattedUrlString.startsWith("https://")
3895 || unformattedUrlString.startsWith("file://")) {
3896 // Add `https://` at the beginning if there is no protocol. Otherwise the app will segfault.
3897 if (!unformattedUrlString.startsWith("http") && !unformattedUrlString.startsWith("file://") && !unformattedUrlString.startsWith("content://")) {
3898 unformattedUrlString = "https://" + unformattedUrlString;
3901 // Initialize `unformattedUrl`.
3902 URL unformattedUrl = null;
3904 // 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.
3906 unformattedUrl = new URL(unformattedUrlString);
3907 } catch (MalformedURLException e) {
3908 e.printStackTrace();
3911 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3912 String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3913 String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3914 String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3915 String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3916 String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3919 Uri.Builder formattedUri = new Uri.Builder();
3920 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3922 // Decode `formattedUri` as a `String` in `UTF-8`.
3924 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3925 } catch (UnsupportedEncodingException exception) {
3926 // Load a blank string.
3927 formattedUrlString = "";
3929 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3930 // Load a blank string.
3931 formattedUrlString = "";
3932 } else { // Search for the contents of the URL box.
3933 // Create an encoded URL String.
3934 String encodedUrlString;
3936 // Sanitize the search input.
3938 encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3939 } catch (UnsupportedEncodingException exception) {
3940 encodedUrlString = "";
3943 // Add the base search URL.
3944 formattedUrlString = searchURL + encodedUrlString;
3947 // 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.
3948 urlTextBox.clearFocus();
3951 loadUrl(formattedUrlString);
3954 private void loadUrl(String url) {// Apply any custom domain settings.
3955 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3956 formattedUrlString = url;
3958 // Apply the domain settings.
3959 applyDomainSettings(url, true, false);
3961 // If loading a website, set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3962 urlIsLoading = !url.equals("");
3965 mainWebView.loadUrl(url, customHeaders);
3968 public void findPreviousOnPage(View view) {
3969 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3970 mainWebView.findNext(false);
3973 public void findNextOnPage(View view) {
3974 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3975 mainWebView.findNext(true);
3978 public void closeFindOnPage(View view) {
3979 // Delete the contents of `find_on_page_edittext`.
3980 findOnPageEditText.setText(null);
3982 // Clear the highlighted phrases.
3983 mainWebView.clearMatches();
3985 // Hide the Find on Page `RelativeLayout`.
3986 findOnPageLinearLayout.setVisibility(View.GONE);
3988 // Show the URL app bar.
3989 supportAppBar.setVisibility(View.VISIBLE);
3991 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3992 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3995 private void applyAppSettings() {
3996 // Get a handle for the shared preferences.
3997 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3999 // Store the values from the shared preferences in variables.
4000 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
4001 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
4002 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
4003 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
4004 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
4005 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
4006 downloadWithExternalApp = sharedPreferences.getBoolean("download_with_external_app", false);
4008 // Apply the proxy through Orbot settings.
4009 applyProxyThroughOrbot(false);
4011 // Set Do Not Track status.
4012 if (doNotTrackEnabled) {
4013 customHeaders.put("DNT", "1");
4015 customHeaders.remove("DNT");
4018 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
4019 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
4020 if (hideSystemBarsOnFullscreen) { // Hide everything.
4021 // Remove the translucent navigation setting if it is currently flagged.
4022 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
4024 // Remove the translucent status bar overlay.
4025 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4027 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
4028 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
4030 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
4031 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
4032 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
4034 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
4035 } else { // Hide everything except the status and navigation bars.
4036 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
4037 rootCoordinatorLayout.setSystemUiVisibility(0);
4039 // Add the translucent status flag if it is unset.
4040 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4042 if (translucentNavigationBarOnFullscreen) {
4043 // Set the navigation bar to be translucent.
4044 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
4046 // Set the navigation bar to be black.
4047 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
4050 } else { // Privacy Browser is not in full screen browsing mode.
4051 // 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.
4052 inFullScreenBrowsingMode = false;
4054 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
4055 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
4059 // Show the `BannerAd` in the free flavor.
4060 if (BuildConfig.FLAVOR.contentEquals("free")) {
4061 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
4062 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.google_app_id), getString(R.string.ad_unit_id));
4065 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
4066 rootCoordinatorLayout.setSystemUiVisibility(0);
4068 // Remove the translucent navigation bar flag if it is set.
4069 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
4071 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
4072 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
4074 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
4075 rootCoordinatorLayout.setFitsSystemWindows(true);
4079 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
4080 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
4081 @SuppressWarnings("deprecation")
4082 private boolean applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
4083 // Get the current user agent.
4084 String initialUserAgent = mainWebView.getSettings().getUserAgentString();
4086 // Initialize a variable to track if the user agent changes.
4087 boolean userAgentChanged = false;
4089 // Parse the URL into a URI.
4090 Uri uri = Uri.parse(url);
4092 // Extract the domain from `uri`.
4093 String hostName = uri.getHost();
4095 // Initialize `loadingNewDomainName`.
4096 boolean loadingNewDomainName;
4098 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
4099 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
4100 //noinspection SimplifiableIfStatement
4101 if ((hostName == null) || (currentDomainName == null)) {
4102 loadingNewDomainName = true;
4103 } else { // Determine if `hostName` equals `currentDomainName`.
4104 loadingNewDomainName = !hostName.equals(currentDomainName);
4107 // Strings don't like to be null.
4108 if (hostName == null) {
4112 // 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.
4113 if (loadingNewDomainName) {
4114 // Set the new `hostname` as the `currentDomainName`.
4115 currentDomainName = hostName;
4117 // Reset `ignorePinnedSslCertificate`.
4118 ignorePinnedSslCertificate = false;
4120 // Reset the favorite icon if specified.
4121 if (resetFavoriteIcon) {
4122 favoriteIconBitmap = favoriteIconDefaultBitmap;
4123 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
4126 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
4127 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
4129 // Get a full cursor from `domainsDatabaseHelper`.
4130 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
4132 // Initialize `domainSettingsSet`.
4133 Set<String> domainSettingsSet = new HashSet<>();
4135 // Get the domain name column index.
4136 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
4138 // Populate `domainSettingsSet`.
4139 for (int i = 0; i < domainNameCursor.getCount(); i++) {
4140 // Move `domainsCursor` to the current row.
4141 domainNameCursor.moveToPosition(i);
4143 // Store the domain name in `domainSettingsSet`.
4144 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
4147 // Close `domainNameCursor.
4148 domainNameCursor.close();
4150 // Initialize variables to track if domain settings will be applied and, if so, under which name.
4151 domainSettingsApplied = false;
4152 String domainNameInDatabase = null;
4154 // Check the hostname.
4155 if (domainSettingsSet.contains(hostName)) {
4156 domainSettingsApplied = true;
4157 domainNameInDatabase = hostName;
4160 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
4161 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
4162 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
4163 // Apply the domain settings.
4164 domainSettingsApplied = true;
4166 // Store the applied domain names as it appears in the database.
4167 domainNameInDatabase = "*." + hostName;
4170 // Strip out the lowest subdomain of of the host name.
4171 hostName = hostName.substring(hostName.indexOf(".") + 1);
4175 // Get a handle for the shared preference.
4176 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4178 // Store the general preference information.
4179 String defaultFontSizeString = sharedPreferences.getString("font_size", getString(R.string.font_size_default_value));
4180 String defaultUserAgentName = sharedPreferences.getString("user_agent", getString(R.string.user_agent_default_value));
4181 defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", getString(R.string.custom_user_agent_default_value));
4182 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
4183 nightMode = sharedPreferences.getBoolean("night_mode", false);
4184 boolean displayWebpageImages = sharedPreferences.getBoolean("display_webpage_images", true);
4186 if (domainSettingsApplied) { // The url has custom domain settings.
4187 // Get a cursor for the current host and move it to the first position.
4188 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
4189 currentHostDomainSettingsCursor.moveToFirst();
4191 // Get the settings from the cursor.
4192 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
4193 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
4194 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
4195 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
4196 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
4197 // Form data can be removed once the minimum API >= 26.
4198 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
4199 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
4200 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
4201 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
4202 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
4203 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
4204 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
4205 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
4206 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
4207 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
4208 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
4209 int displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
4210 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
4211 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
4212 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
4213 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
4214 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
4215 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
4216 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
4218 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
4219 switch (nightModeInt) {
4220 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
4224 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
4229 // Store the domain JavaScript status. This is used by the options menu night mode toggle.
4230 domainSettingsJavaScriptEnabled = javaScriptEnabled;
4232 // Enable JavaScript if night mode is enabled.
4234 javaScriptEnabled = true;
4237 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
4238 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
4239 pinnedDomainSslStartDate = null;
4241 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
4244 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
4245 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
4246 pinnedDomainSslEndDate = null;
4248 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
4251 // Close `currentHostDomainSettingsCursor`.
4252 currentHostDomainSettingsCursor.close();
4254 // Apply the domain settings.
4255 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4256 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4257 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4259 // Apply the form data setting if the API < 26.
4260 if (Build.VERSION.SDK_INT < 26) {
4261 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4264 // Apply the font size.
4265 if (fontSize == 0) { // Apply the default font size.
4266 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4267 } else { // Apply the specified font size.
4268 mainWebView.getSettings().setTextZoom(fontSize);
4271 // Set third-party cookies status if API >= 21.
4272 if (Build.VERSION.SDK_INT >= 21) {
4273 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4276 // 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.
4277 // <https://redmine.stoutner.com/issues/160>
4278 if (!urlIsLoading) {
4279 // Set the user agent.
4280 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
4281 // Get the array position of the default user agent name.
4282 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4284 // Set the user agent according to the system default.
4285 switch (defaultUserAgentArrayPosition) {
4286 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4287 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4288 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4291 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4292 // Set the user agent to `""`, which uses the default value.
4293 mainWebView.getSettings().setUserAgentString("");
4296 case SETTINGS_CUSTOM_USER_AGENT:
4297 // Set the custom user agent.
4298 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4302 // Get the user agent string from the user agent data array
4303 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
4305 } else { // Set the user agent according to the stored name.
4306 // Get the array position of the user agent name.
4307 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
4309 switch (userAgentArrayPosition) {
4310 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
4311 mainWebView.getSettings().setUserAgentString(userAgentName);
4314 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4315 // Set the user agent to `""`, which uses the default value.
4316 mainWebView.getSettings().setUserAgentString("");
4320 // Get the user agent string from the user agent data array.
4321 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4325 // Store the applied user agent string, which is used in the View Source activity.
4326 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4328 // Update the user agent change tracker.
4329 userAgentChanged = !appliedUserAgentString.equals(initialUserAgent);
4332 // Set swipe to refresh.
4333 switch (swipeToRefreshInt) {
4334 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
4335 // Set swipe to refresh according to the default.
4336 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4339 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
4340 // Enable swipe to refresh.
4341 swipeRefreshLayout.setEnabled(true);
4344 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
4345 // Disable swipe to refresh.
4346 swipeRefreshLayout.setEnabled(false);
4349 // Set the loading of webpage images.
4350 switch (displayWebpageImagesInt) {
4351 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4352 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4355 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4356 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4359 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4360 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4364 // 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.
4366 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4368 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4370 } else { // The new URL does not have custom domain settings. Load the defaults.
4371 // Store the values from `sharedPreferences` in variables.
4372 javaScriptEnabled = sharedPreferences.getBoolean("javascript", false);
4373 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies", false);
4374 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies", false);
4375 domStorageEnabled = sharedPreferences.getBoolean("dom_storage", false);
4376 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data", false); // Form data can be removed once the minimum API >= 26.
4377 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
4378 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
4379 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboys_annoyance_list", true);
4380 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboys_social_blocking_list", true);
4381 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
4382 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
4384 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4386 javaScriptEnabled = true;
4389 // Apply the default settings.
4390 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4391 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4392 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4393 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4394 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
4396 // Apply the form data setting if the API < 26.
4397 if (Build.VERSION.SDK_INT < 26) {
4398 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4401 // Reset the pinned SSL certificate information.
4402 domainSettingsDatabaseId = -1;
4403 pinnedDomainSslCertificate = false;
4404 pinnedDomainSslIssuedToCNameString = "";
4405 pinnedDomainSslIssuedToONameString = "";
4406 pinnedDomainSslIssuedToUNameString = "";
4407 pinnedDomainSslIssuedByCNameString = "";
4408 pinnedDomainSslIssuedByONameString = "";
4409 pinnedDomainSslIssuedByUNameString = "";
4410 pinnedDomainSslStartDate = null;
4411 pinnedDomainSslEndDate = null;
4413 // Set third-party cookies status if API >= 21.
4414 if (Build.VERSION.SDK_INT >= 21) {
4415 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4418 // 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.
4419 // <https://redmine.stoutner.com/issues/160>
4420 if (!urlIsLoading) {
4421 // Get the array position of the user agent name.
4422 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
4424 // Set the user agent.
4425 switch (userAgentArrayPosition) {
4426 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
4427 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
4428 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4431 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4432 // Set the user agent to `""`, which uses the default value.
4433 mainWebView.getSettings().setUserAgentString("");
4436 case SETTINGS_CUSTOM_USER_AGENT:
4437 // Set the custom user agent.
4438 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4442 // Get the user agent string from the user agent data array
4443 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4446 // Store the applied user agent string, which is used in the View Source activity.
4447 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4449 // Update the user agent change tracker.
4450 userAgentChanged = !appliedUserAgentString.equals(initialUserAgent);
4453 // Set the loading of webpage images.
4454 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImages);
4456 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4457 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4460 // Close the domains database helper.
4461 domainsDatabaseHelper.close();
4463 // Update the privacy icons, but only if `mainMenu` has already been populated.
4464 if (mainMenu != null) {
4465 updatePrivacyIcons(true);
4469 // Reload the website if returning from the Domains activity.
4470 if (reloadWebsite) {
4471 mainWebView.reload();
4474 // Return the user agent changed status.
4475 return userAgentChanged;
4478 private void applyProxyThroughOrbot(boolean reloadWebsite) {
4479 // Get a handle for the shared preferences.
4480 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
4482 // Get the search preferences.
4483 String homepageString = sharedPreferences.getString("homepage", getString(R.string.homepage_default_value));
4484 String torHomepageString = sharedPreferences.getString("tor_homepage", getString(R.string.tor_homepage_default_value));
4485 String torSearchString = sharedPreferences.getString("tor_search", getString(R.string.tor_search_default_value));
4486 String torSearchCustomUrlString = sharedPreferences.getString("tor_search_custom_url", getString(R.string.tor_search_custom_url_default_value));
4487 String searchString = sharedPreferences.getString("search", getString(R.string.search_default_value));
4488 String searchCustomUrlString = sharedPreferences.getString("search_custom_url", getString(R.string.search_custom_url_default_value));
4490 // Set the homepage, search, and proxy options.
4491 if (proxyThroughOrbot) { // Set the Tor options.
4492 // Set `torHomepageString` as `homepage`.
4493 homepage = torHomepageString;
4495 // If formattedUrlString is null assign the homepage to it.
4496 if (formattedUrlString == null) {
4497 formattedUrlString = homepage;
4500 // Set the search URL.
4501 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
4502 searchURL = torSearchCustomUrlString;
4503 } else { // Use the string from the pre-built list.
4504 searchURL = torSearchString;
4507 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
4508 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
4510 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
4512 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
4514 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
4517 // Check to see if Orbot is ready.
4518 if (!orbotStatus.equals("ON")) { // Orbot is not ready.
4519 // Set `waitingForOrbot`.
4520 waitingForOrbot = true;
4522 // Disable the wide view port so that the waiting for Orbot text is displayed correctly.
4523 mainWebView.getSettings().setUseWideViewPort(false);
4525 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
4526 mainWebView.loadData(waitingForOrbotHtmlString, "text/html", null);
4527 } else if (reloadWebsite) { // Orbot is ready and the website should be reloaded.
4528 // Reload the website.
4529 mainWebView.reload();
4531 } else { // Set the non-Tor options.
4532 // Set `homepageString` as `homepage`.
4533 homepage = homepageString;
4535 // If formattedUrlString is null assign the homepage to it.
4536 if (formattedUrlString == null) {
4537 formattedUrlString = homepage;
4540 // Set the search URL.
4541 if (searchString.equals("Custom URL")) { // Get the custom URL string.
4542 searchURL = searchCustomUrlString;
4543 } else { // Use the string from the pre-built list.
4544 searchURL = searchString;
4547 // Reset the proxy to default. The host is `""` and the port is `"0"`.
4548 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
4550 // Set the default `appBar` background. `this` refers to the context.
4552 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
4554 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
4557 // Reset `waitingForOrbot.
4558 waitingForOrbot = false;
4560 // Reload the website if requested.
4561 if (reloadWebsite) {
4562 mainWebView.reload();
4567 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4568 // Get handles for the menu items.
4569 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4570 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4571 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4572 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4574 // Update the privacy icon.
4575 if (javaScriptEnabled) { // JavaScript is enabled.
4576 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4577 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4578 privacyMenuItem.setIcon(R.drawable.warning);
4579 } else { // All the dangerous features are disabled.
4580 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4583 // Update the first-party cookies icon.
4584 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4585 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4586 } else { // First-party cookies are disabled.
4588 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4590 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4594 // Update the DOM storage icon.
4595 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4596 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4597 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4599 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4601 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4603 } else { // JavaScript is disabled, so DOM storage is ghosted.
4605 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4607 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4611 // Update the refresh icon.
4613 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4615 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4618 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4619 if (runInvalidateOptionsMenu) {
4620 invalidateOptionsMenu();
4624 private void openUrlWithExternalApp(String url) {
4625 // Create a download intent. Not specifying the action type will display the maximum number of options.
4626 Intent downloadIntent = new Intent();
4628 // Set the URI and the mime type. `"*/*"` will display the maximum number of options.
4629 downloadIntent.setDataAndType(Uri.parse(url), "text/html");
4631 // Flag the intent to open in a new task.
4632 downloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4634 // Show the chooser.
4635 startActivity(Intent.createChooser(downloadIntent, getString(R.string.open_with)));
4638 private void highlightUrlText() {
4639 // Get the URL string.
4640 String urlString = urlTextBox.getText().toString();
4642 // Highlight the URL according to the protocol.
4643 if (urlString.startsWith("file://")) { // This is a file URL.
4644 // De-emphasize only the protocol.
4645 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4646 } else if (urlString.startsWith("content://")) {
4647 // De-emphasize only the protocol.
4648 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 10, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4649 } else { // This is a web URL.
4650 // Get the index of the `/` immediately after the domain name.
4651 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4653 // Create a base URL string.
4656 // Get the base URL.
4657 if (endOfDomainName > 0) { // There is at least one character after the base URL.
4658 // Get the base URL.
4659 baseUrl = urlString.substring(0, endOfDomainName);
4660 } else { // There are no characters after the base URL.
4661 // Set the base URL to be the entire URL string.
4662 baseUrl = urlString;
4665 // Get the index of the last `.` in the domain.
4666 int lastDotIndex = baseUrl.lastIndexOf(".");
4668 // Get the index of the penultimate `.` in the domain.
4669 int penultimateDotIndex = baseUrl.lastIndexOf(".", lastDotIndex - 1);
4671 // Markup the beginning of the URL.
4672 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4673 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4675 // De-emphasize subdomains.
4676 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4677 urlTextBox.getText().setSpan(initialGrayColorSpan, 7, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4679 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4680 if (penultimateDotIndex > 0) { // There is more than one subdomain in the domain name.
4681 // De-emphasize the protocol and the additional subdomains.
4682 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, penultimateDotIndex + 1, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4683 } else { // There is only one subdomain in the domain name.
4684 // De-emphasize only the protocol.
4685 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4689 // De-emphasize the text after the domain name.
4690 if (endOfDomainName > 0) {
4691 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4696 private void loadBookmarksFolder() {
4697 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4698 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4700 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4701 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4703 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4704 // Inflate the individual item layout. `false` does not attach it to the root.
4705 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4709 public void bindView(View view, Context context, Cursor cursor) {
4710 // Get handles for the views.
4711 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4712 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4714 // Get the favorite icon byte array from the cursor.
4715 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4717 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4718 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4720 // Display the bitmap in `bookmarkFavoriteIcon`.
4721 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4723 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4724 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4725 bookmarkNameTextView.setText(bookmarkNameString);
4727 // Make the font bold for folders.
4728 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4729 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4730 } else { // Reset the font to default for normal bookmarks.
4731 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4736 // Populate the `ListView` with the adapter.
4737 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4739 // Set the bookmarks drawer title.
4740 if (currentBookmarksFolder.isEmpty()) {
4741 bookmarksTitleTextView.setText(R.string.bookmarks);
4743 bookmarksTitleTextView.setText(currentBookmarksFolder);