2 * Copyright © 2015-2018 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.Manifest;
25 import android.annotation.SuppressLint;
26 import android.app.DialogFragment;
27 import android.app.DownloadManager;
28 import android.content.ActivityNotFoundException;
29 import android.content.BroadcastReceiver;
30 import android.content.ClipData;
31 import android.content.ClipboardManager;
32 import android.content.Context;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.content.SharedPreferences;
36 import android.content.pm.PackageManager;
37 import android.content.res.Configuration;
38 import android.database.Cursor;
39 import android.graphics.Bitmap;
40 import android.graphics.BitmapFactory;
41 import android.graphics.Typeface;
42 import android.graphics.drawable.BitmapDrawable;
43 import android.graphics.drawable.Drawable;
44 import android.net.Uri;
45 import android.net.http.SslCertificate;
46 import android.net.http.SslError;
47 import android.os.Build;
48 import android.os.Bundle;
49 import android.os.Environment;
50 import android.os.Handler;
51 import android.preference.PreferenceManager;
52 import android.print.PrintDocumentAdapter;
53 import android.print.PrintManager;
54 import android.support.annotation.NonNull;
55 import android.support.design.widget.CoordinatorLayout;
56 import android.support.design.widget.FloatingActionButton;
57 import android.support.design.widget.NavigationView;
58 import android.support.design.widget.Snackbar;
59 import android.support.v4.app.ActivityCompat;
60 import android.support.v4.content.ContextCompat;
61 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
62 import android.support.v4.content.pm.ShortcutInfoCompat;
63 import android.support.v4.content.pm.ShortcutManagerCompat;
64 import android.support.v4.graphics.drawable.IconCompat;
65 import android.support.v4.view.GravityCompat;
66 import android.support.v4.widget.DrawerLayout;
67 import android.support.v4.widget.SwipeRefreshLayout;
68 import android.support.v7.app.ActionBar;
69 import android.support.v7.app.ActionBarDrawerToggle;
70 import android.support.v7.app.AppCompatActivity;
71 import android.support.v7.app.AppCompatDialogFragment;
72 import android.support.v7.widget.Toolbar;
73 import android.text.Editable;
74 import android.text.Spanned;
75 import android.text.TextWatcher;
76 import android.text.style.ForegroundColorSpan;
77 import android.util.Patterns;
78 import android.view.ContextMenu;
79 import android.view.GestureDetector;
80 import android.view.KeyEvent;
81 import android.view.Menu;
82 import android.view.MenuItem;
83 import android.view.MotionEvent;
84 import android.view.View;
85 import android.view.ViewGroup;
86 import android.view.WindowManager;
87 import android.view.inputmethod.InputMethodManager;
88 import android.webkit.CookieManager;
89 import android.webkit.HttpAuthHandler;
90 import android.webkit.SslErrorHandler;
91 import android.webkit.ValueCallback;
92 import android.webkit.WebBackForwardList;
93 import android.webkit.WebChromeClient;
94 import android.webkit.WebResourceResponse;
95 import android.webkit.WebStorage;
96 import android.webkit.WebView;
97 import android.webkit.WebViewClient;
98 import android.webkit.WebViewDatabase;
99 import android.widget.ArrayAdapter;
100 import android.widget.CursorAdapter;
101 import android.widget.EditText;
102 import android.widget.FrameLayout;
103 import android.widget.ImageView;
104 import android.widget.LinearLayout;
105 import android.widget.ListView;
106 import android.widget.ProgressBar;
107 import android.widget.RadioButton;
108 import android.widget.RelativeLayout;
109 import android.widget.TextView;
111 import com.stoutner.privacybrowser.BuildConfig;
112 import com.stoutner.privacybrowser.R;
113 import com.stoutner.privacybrowser.dialogs.AdConsentDialog;
114 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
116 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
117 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
118 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
119 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
120 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
121 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
122 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
123 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
124 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
125 import com.stoutner.privacybrowser.helpers.AdHelper;
126 import com.stoutner.privacybrowser.helpers.BlockListHelper;
127 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
128 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
129 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
130 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
131 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
133 import java.io.ByteArrayInputStream;
134 import java.io.ByteArrayOutputStream;
136 import java.io.IOException;
137 import java.io.UnsupportedEncodingException;
138 import java.net.MalformedURLException;
140 import java.net.URLDecoder;
141 import java.net.URLEncoder;
142 import java.util.ArrayList;
143 import java.util.Date;
144 import java.util.HashMap;
145 import java.util.HashSet;
146 import java.util.List;
147 import java.util.Map;
148 import java.util.Set;
150 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
151 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
152 CreateHomeScreenShortcutDialog.CreateHomeScreenShortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
153 DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
154 HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
155 SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
157 // `darkTheme` is public static so it can be accessed from everywhere.
158 public static boolean darkTheme;
160 // `allowScreenshots` is public static so it can be accessed from everywhere. It is also used in `onCreate()`.
161 public static boolean allowScreenshots;
163 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
164 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
165 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
166 public static Bitmap favoriteIconBitmap;
168 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
169 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
170 public static String formattedUrlString;
172 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
173 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
174 public static SslCertificate sslCertificate;
176 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()` and `onResume()`.
177 public static String orbotStatus;
179 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
180 public static String webViewTitle;
182 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
183 public static String appliedUserAgentString;
185 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
186 public static boolean reloadOnRestart;
188 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`. It is also used in `onRestart()`.
189 public static boolean loadUrlOnRestart;
191 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
192 public static boolean restartFromBookmarksActivity;
194 // The block list versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
195 public static String easyListVersion;
196 public static String easyPrivacyVersion;
197 public static String fanboysAnnoyanceVersion;
198 public static String fanboysSocialVersion;
199 public static String ultraPrivacyVersion;
201 // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`. They are also used in `onCreate()`.
202 public static List<String[]> resourceRequests;
203 public static String[] whiteListResultStringArray;
204 public final static int REQUEST_DISPOSITION = 0;
205 public final static int REQUEST_URL = 1;
206 public final static int REQUEST_BLOCKLIST = 2;
207 public final static int REQUEST_SUBLIST = 3;
208 public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
209 public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
211 public final static int REQUEST_DEFAULT = 0;
212 public final static int REQUEST_ALLOWED = 1;
213 public final static int REQUEST_THIRD_PARTY = 2;
214 public final static int REQUEST_BLOCKED = 3;
216 public final static int MAIN_WHITELIST = 1;
217 public final static int FINAL_WHITELIST = 2;
218 public final static int DOMAIN_WHITELIST = 3;
219 public final static int DOMAIN_INITIAL_WHITELIST = 4;
220 public final static int DOMAIN_FINAL_WHITELIST = 5;
221 public final static int THIRD_PARTY_WHITELIST = 6;
222 public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
223 public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
225 public final static int MAIN_BLACKLIST = 9;
226 public final static int INITIAL_BLACKLIST = 10;
227 public final static int FINAL_BLACKLIST = 11;
228 public final static int DOMAIN_BLACKLIST = 12;
229 public final static int DOMAIN_INITIAL_BLACKLIST = 13;
230 public final static int DOMAIN_FINAL_BLACKLIST = 14;
231 public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
232 public final static int THIRD_PARTY_BLACKLIST = 16;
233 public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
234 public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
235 public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
236 public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
237 public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
238 public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
240 // `blockAllThirdPartyRequests` is public static so it can be accessed from `RequestsActivity`.
241 // It is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`
242 public static boolean blockAllThirdPartyRequests;
244 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
245 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
246 public static String currentBookmarksFolder;
248 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
249 public static int domainSettingsDatabaseId;
251 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
252 public static String pinnedDomainSslIssuedToCNameString;
253 public static String pinnedDomainSslIssuedToONameString;
254 public static String pinnedDomainSslIssuedToUNameString;
255 public static String pinnedDomainSslIssuedByCNameString;
256 public static String pinnedDomainSslIssuedByONameString;
257 public static String pinnedDomainSslIssuedByUNameString;
258 public static Date pinnedDomainSslStartDate;
259 public static Date pinnedDomainSslEndDate;
261 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
262 public final static int UNRECOGNIZED_USER_AGENT = -1;
263 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
264 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
265 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
266 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
267 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
270 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
271 private ActionBar appBar;
273 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
274 private boolean navigatingHistory;
276 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
277 private Bitmap favoriteIconDefaultBitmap;
279 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
280 private DrawerLayout drawerLayout;
282 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
283 private CoordinatorLayout rootCoordinatorLayout;
285 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
286 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
287 private WebView mainWebView;
289 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
290 private FrameLayout fullScreenVideoFrameLayout;
292 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
293 private SwipeRefreshLayout swipeRefreshLayout;
295 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
296 private RelativeLayout urlAppBarRelativeLayout;
298 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
299 private ImageView favoriteIconImageView;
301 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
302 private CookieManager cookieManager;
304 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
305 private final Map<String, String> customHeaders = new HashMap<>();
307 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
308 private boolean javaScriptEnabled;
310 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
311 private boolean firstPartyCookiesEnabled;
313 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
314 private boolean thirdPartyCookiesEnabled;
316 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
317 private boolean domStorageEnabled;
319 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`. It can be removed once the minimum API >= 26.
320 private boolean saveFormDataEnabled;
322 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
323 private boolean nightMode;
325 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
326 private boolean displayWebpageImagesBoolean;
328 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
329 private String homepage;
331 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
332 private String searchURL;
334 // The block list variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
335 private boolean easyListEnabled;
336 private boolean easyPrivacyEnabled;
337 private boolean fanboysAnnoyanceListEnabled;
338 private boolean fanboysSocialBlockingListEnabled;
339 private boolean ultraPrivacyEnabled;
341 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
342 private Runtime privacyBrowserRuntime;
344 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
345 private boolean proxyThroughOrbot;
347 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
348 private boolean incognitoModeEnabled;
350 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
351 private boolean fullScreenBrowsingModeEnabled;
353 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
354 private boolean inFullScreenBrowsingMode;
356 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
357 private boolean hideSystemBarsOnFullscreen;
359 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
360 private boolean translucentNavigationBarOnFullscreen;
362 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
363 private boolean reapplyDomainSettingsOnRestart;
365 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
366 private boolean reapplyAppSettingsOnRestart;
368 // `displayingFullScreenVideo` is used in `onCreate()` and `onResume()`.
369 private boolean displayingFullScreenVideo;
371 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
372 private String currentDomainName;
374 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
375 private boolean ignorePinnedSslCertificate;
377 // `orbotStatusBroadcastReciever` is used in `onCreate()` and `onDestroy()`.
378 private BroadcastReceiver orbotStatusBroadcastReceiver;
380 // `waitingForOrbot` is used in `onCreate()`, `onResume()`, and `applyAppSettings()`.
381 private boolean waitingForOrbot;
383 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
384 private boolean domainSettingsApplied;
386 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
387 private int displayWebpageImagesInt;
389 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
390 private boolean onTheFlyDisplayImagesSet;
392 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
393 private String waitingForOrbotHTMLString;
395 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
396 private String privateDataDirectoryString;
398 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
399 private LinearLayout findOnPageLinearLayout;
401 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
402 private EditText findOnPageEditText;
404 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
405 private Menu mainMenu;
407 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
408 private ActionBarDrawerToggle drawerToggle;
410 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
411 private Toolbar supportAppBar;
413 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
414 private EditText urlTextBox;
416 // The color spans are used in `onCreate()` and `highlightUrlText()`.
417 private ForegroundColorSpan redColorSpan;
418 private ForegroundColorSpan initialGrayColorSpan;
419 private ForegroundColorSpan finalGrayColorSpan;
421 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
422 private SslErrorHandler sslErrorHandler;
424 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
425 private static HttpAuthHandler httpAuthHandler;
427 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
428 private InputMethodManager inputMethodManager;
430 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
431 private RelativeLayout mainWebViewRelativeLayout;
433 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
434 private boolean urlIsLoading;
436 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
437 private boolean pinnedDomainSslCertificate;
439 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
440 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
442 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
443 private ListView bookmarksListView;
445 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
446 private TextView bookmarksTitleTextView;
448 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
449 private Cursor bookmarksCursor;
451 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
452 private CursorAdapter bookmarksCursorAdapter;
454 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
455 private String oldFolderNameString;
457 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
458 private ValueCallback<Uri[]> fileChooserCallback;
460 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
461 private String downloadUrl;
462 private String downloadContentDisposition;
463 private long downloadContentLength;
465 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
466 private String downloadImageUrl;
468 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
469 private ArrayAdapter<CharSequence> userAgentNamesArray;
470 private String[] userAgentDataArray;
472 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
473 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
474 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
477 // 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.
478 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
479 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
480 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
481 @SuppressWarnings("deprecation")
482 protected void onCreate(Bundle savedInstanceState) {
483 // Get a handle for the shared preferences.
484 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
486 // Get the theme and screenshot preferences.
487 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
488 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
490 // Disable screenshots if not allowed.
491 if (!allowScreenshots) {
492 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
495 // Set the activity theme.
497 setTheme(R.style.PrivacyBrowserDark);
499 setTheme(R.style.PrivacyBrowserLight);
502 // Run the default commands.
503 super.onCreate(savedInstanceState);
505 // Set the content view.
506 setContentView(R.layout.main_drawerlayout);
508 // Get a handle for `inputMethodManager`.
509 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
511 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
512 supportAppBar = findViewById(R.id.app_bar);
513 setSupportActionBar(supportAppBar);
514 appBar = getSupportActionBar();
516 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
517 assert appBar != null;
519 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
520 appBar.setCustomView(R.layout.url_app_bar);
521 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
523 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
524 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
525 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
526 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
528 // Get a handle for `urlTextBox`.
529 urlTextBox = findViewById(R.id.url_edittext);
531 // Remove the formatting from `urlTextBar` when the user is editing the text.
532 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
533 if (hasFocus) { // The user is editing `urlTextBox`.
534 // Remove the highlighting.
535 urlTextBox.getText().removeSpan(redColorSpan);
536 urlTextBox.getText().removeSpan(initialGrayColorSpan);
537 urlTextBox.getText().removeSpan(finalGrayColorSpan);
538 } else { // The user has stopped editing `urlTextBox`.
539 // Reapply the highlighting.
544 // Set the go button on the keyboard to load the URL in `urlTextBox`.
545 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
546 // If the event is a key-down event on the `enter` button, load the URL.
547 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
548 // Load the URL into the mainWebView and consume the event.
550 loadUrlFromTextBox();
551 } catch (UnsupportedEncodingException e) {
554 // If the enter key was pressed, consume the event.
557 // If any other key was pressed, do not consume the event.
562 // Set `waitingForOrbotHTMLString`.
563 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
565 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
566 currentDomainName = "";
567 orbotStatus = "unknown";
568 waitingForOrbot = false;
570 // Create an Orbot status `BroadcastReceiver`.
571 orbotStatusBroadcastReceiver = new BroadcastReceiver() {
573 public void onReceive(Context context, Intent intent) {
574 // Store the content of the status message in `orbotStatus`.
575 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
577 // If we are waiting on Orbot, load the website now that Orbot is connected.
578 if (orbotStatus.equals("ON") && waitingForOrbot) {
579 // Reset `waitingForOrbot`.
580 waitingForOrbot = false;
582 // Load `formattedUrlString
583 loadUrl(formattedUrlString);
588 // Register `orbotStatusBroadcastReceiver` on `this` context.
589 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
591 // Get handles for views that need to be accessed.
592 drawerLayout = findViewById(R.id.drawerlayout);
593 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
594 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
595 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
596 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
597 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
598 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
599 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
600 mainWebView = findViewById(R.id.main_webview);
601 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
602 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
603 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
604 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
605 favoriteIconImageView = findViewById(R.id.favorite_icon);
607 // 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.
609 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
610 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
611 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
612 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
614 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
615 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
616 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
617 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
620 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
621 launchBookmarksActivityFab.setOnClickListener(v -> {
622 // Create an intent to launch the bookmarks activity.
623 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
625 // Include the current folder with the `Intent`.
626 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
629 startActivity(bookmarksIntent);
632 // Set the create new bookmark folder FAB to display an alert dialog.
633 createBookmarkFolderFab.setOnClickListener(v -> {
634 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
635 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
636 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
639 // Set the create new bookmark FAB to display an alert dialog.
640 createBookmarkFab.setOnClickListener(view -> {
641 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
642 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
643 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
646 // Create a double-tap listener to toggle full-screen mode.
647 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
648 // Override `onDoubleTap()`. All other events are handled using the default settings.
650 public boolean onDoubleTap(MotionEvent event) {
651 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
652 // Toggle `inFullScreenBrowsingMode`.
653 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
655 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
656 // Hide the `appBar`.
659 // Hide the banner ad in the free flavor.
660 if (BuildConfig.FLAVOR.contentEquals("free")) {
661 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
662 AdHelper.hideAd(findViewById(R.id.adview));
665 // Modify the system bars.
666 if (hideSystemBarsOnFullscreen) { // Hide everything.
667 // Remove the translucent overlays.
668 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
670 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
671 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
673 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
674 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
675 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
677 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
679 // Set `rootCoordinatorLayout` to fill the whole screen.
680 rootCoordinatorLayout.setFitsSystemWindows(false);
681 } else { // Hide everything except the status and navigation bars.
682 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
683 rootCoordinatorLayout.setFitsSystemWindows(false);
685 // 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.
686 if (translucentNavigationBarOnFullscreen) {
687 // Set the navigation bar to be translucent.
688 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
691 } else { // Switch to normal viewing mode.
692 // Show the `appBar`.
695 // Show the `BannerAd` in the free flavor.
696 if (BuildConfig.FLAVOR.contentEquals("free")) {
697 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
698 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
701 // Remove the translucent navigation bar flag if it is set.
702 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
704 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
705 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
707 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
708 rootCoordinatorLayout.setSystemUiVisibility(0);
710 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
711 rootCoordinatorLayout.setFitsSystemWindows(true);
714 // Consume the double-tap.
716 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
722 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
723 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
724 // Call `performClick()` on the view, which is required for accessibility.
727 // Send the `event` to `gestureDetector`.
728 return gestureDetector.onTouchEvent(event);
731 // Update `findOnPageCountTextView`.
732 mainWebView.setFindListener(new WebView.FindListener() {
733 // Get a handle for `findOnPageCountTextView`.
734 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
737 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
738 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
739 // Set `findOnPageCountTextView` to `0/0`.
740 findOnPageCountTextView.setText(R.string.zero_of_zero);
741 } else if (isDoneCounting) { // There are matches.
742 // `activeMatchOrdinal` is zero-based.
743 int activeMatch = activeMatchOrdinal + 1;
745 // Build the match string.
746 String matchString = activeMatch + "/" + numberOfMatches;
748 // Set `findOnPageCountTextView`.
749 findOnPageCountTextView.setText(matchString);
754 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
755 findOnPageEditText.addTextChangedListener(new TextWatcher() {
757 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
762 public void onTextChanged(CharSequence s, int start, int before, int count) {
767 public void afterTextChanged(Editable s) {
768 // Search for the text in `mainWebView`.
769 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
773 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
774 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
775 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
776 // Hide the soft keyboard. `0` indicates no additional flags.
777 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
779 // Consume the event.
781 } else { // A different key was pressed.
782 // Do not consume the event.
787 // Implement swipe to refresh
788 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
789 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
790 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
792 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
793 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
794 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
796 // Listen for touches on the navigation menu.
797 final NavigationView navigationView = findViewById(R.id.navigationview);
798 navigationView.setNavigationItemSelectedListener(this);
800 // 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.
801 final Menu navigationMenu = navigationView.getMenu();
802 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
803 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
804 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
805 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
807 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
808 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
809 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
811 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
812 currentBookmarksFolder = "";
814 // Load the home folder, which is `""` in the database.
815 loadBookmarksFolder();
817 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
818 // Convert the id from long to int to match the format of the bookmarks database.
819 int databaseID = (int) id;
821 // Get the bookmark cursor for this ID and move it to the first row.
822 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
823 bookmarkCursor.moveToFirst();
825 // Act upon the bookmark according to the type.
826 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
827 // Store the new folder name in `currentBookmarksFolder`.
828 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
830 // Load the new folder.
831 loadBookmarksFolder();
832 } else { // The selected bookmark is not a folder.
833 // Load the bookmark URL.
834 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
836 // Close the bookmarks drawer.
837 drawerLayout.closeDrawer(GravityCompat.END);
840 // Close the `Cursor`.
841 bookmarkCursor.close();
844 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
845 // Convert the database ID from `long` to `int`.
846 int databaseId = (int) id;
848 // Find out if the selected bookmark is a folder.
849 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
852 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
853 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
855 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
856 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
857 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
859 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
860 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
861 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
864 // Consume the event.
868 // The `DrawerListener` is used to update the Navigation Menu.
869 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
871 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
875 public void onDrawerOpened(@NonNull View drawerView) {
879 public void onDrawerClosed(@NonNull View drawerView) {
883 public void onDrawerStateChanged(int newState) {
884 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
885 // Initialize a the blocked requests counter.
886 int blockedRequests = 0;
888 // Count the number of blocked requests.
889 for (int i = 0; i < resourceRequests.size(); i++) {
890 // Add the blocked requests.
891 if (Integer.valueOf(resourceRequests.get(i)[REQUEST_DISPOSITION]) == REQUEST_BLOCKED) {
895 // Add the third-party requests if they are blocked.
896 if (blockAllThirdPartyRequests && (Integer.valueOf(resourceRequests.get(i)[REQUEST_DISPOSITION]) == REQUEST_THIRD_PARTY)) {
901 // Update the back, forward, history, and requests menu items.
902 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
903 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
904 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
905 navigationRequestsMenuItem.setTitle(getResources().getString(R.string.requests) + " - " + blockedRequests);
907 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
908 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
910 // Clear the focus from `urlTextBox` if it has it.
911 urlTextBox.clearFocus();
916 // drawerToggle creates the hamburger icon at the start of the AppBar.
917 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
919 // Get a handle for the progress bar.
920 final ProgressBar progressBar = findViewById(R.id.progress_bar);
922 mainWebView.setWebChromeClient(new WebChromeClient() {
923 // Update the progress bar when a page is loading.
925 public void onProgressChanged(WebView view, int progress) {
926 // Inject the night mode CSS if night mode is enabled.
928 // `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
929 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
930 // `border: none` removes all borders, which can also be used to underline text.
931 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
932 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
933 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
934 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
935 // Initialize a `Handler` to display `mainWebView`.
936 Handler displayWebViewHandler = new Handler();
938 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
939 Runnable displayWebViewRunnable = () -> {
940 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
941 if (progressBar.getVisibility() == View.GONE) {
942 mainWebView.setVisibility(View.VISIBLE);
946 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
947 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
951 // Update the progress bar.
952 progressBar.setProgress(progress);
954 // Set the visibility of the progress bar.
955 if (progress < 100) {
956 // Show the progress bar.
957 progressBar.setVisibility(View.VISIBLE);
959 // Hide the progress bar.
960 progressBar.setVisibility(View.GONE);
962 // Display `mainWebView` if night mode is disabled.
963 // 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
964 // currently enabled.
966 mainWebView.setVisibility(View.VISIBLE);
969 //Stop the swipe to refresh indicator if it is running
970 swipeRefreshLayout.setRefreshing(false);
974 // Set the favorite icon when it changes.
976 public void onReceivedIcon(WebView view, Bitmap icon) {
977 // Only update the favorite icon if the website has finished loading.
978 if (progressBar.getVisibility() == View.GONE) {
979 // Save a copy of the favorite icon.
980 favoriteIconBitmap = icon;
982 // Place the favorite icon in the appBar.
983 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
987 // Save a copy of the title when it changes.
989 public void onReceivedTitle(WebView view, String title) {
990 // Save a copy of the title.
991 webViewTitle = title;
994 // Enter full screen video.
996 public void onShowCustomView(View view, CustomViewCallback callback) {
997 // Set the full screen video flag.
998 displayingFullScreenVideo = true;
1000 // Pause the ad if this is the free flavor.
1001 if (BuildConfig.FLAVOR.contentEquals("free")) {
1002 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1003 AdHelper.pauseAd(findViewById(R.id.adview));
1006 // Remove the translucent overlays.
1007 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1009 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1010 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1012 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1013 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1014 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1016 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1018 // Set `rootCoordinatorLayout` to fill the entire screen.
1019 rootCoordinatorLayout.setFitsSystemWindows(false);
1021 // Disable the sliding drawers.
1022 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1024 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1025 fullScreenVideoFrameLayout.addView(view);
1026 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1029 // Exit full screen video.
1031 public void onHideCustomView() {
1032 // Unset the full screen video flag.
1033 displayingFullScreenVideo = true;
1035 // Hide `fullScreenVideoFrameLayout`.
1036 fullScreenVideoFrameLayout.removeAllViews();
1037 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1039 // Enable the sliding drawers.
1040 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1042 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
1043 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
1044 if (hideSystemBarsOnFullscreen) { // Hide everything.
1045 // Remove the translucent navigation setting if it is currently flagged.
1046 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1048 // Remove the translucent status bar overlay.
1049 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1051 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1052 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1054 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1055 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1056 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1058 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1059 } else { // Hide everything except the status and navigation bars.
1060 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1061 rootCoordinatorLayout.setSystemUiVisibility(0);
1063 // Add the translucent status flag if it is unset.
1064 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1066 if (translucentNavigationBarOnFullscreen) {
1067 // Set the navigation bar to be translucent. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1068 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1070 // Set the navigation bar to be black.
1071 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1074 } else { // Switch to normal viewing mode.
1075 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
1076 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
1080 // Show the `BannerAd` in the free flavor.
1081 if (BuildConfig.FLAVOR.contentEquals("free")) {
1082 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1083 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
1086 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1087 rootCoordinatorLayout.setSystemUiVisibility(0);
1089 // Remove the translucent navigation bar flag if it is set.
1090 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1092 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1093 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1095 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1096 rootCoordinatorLayout.setFitsSystemWindows(true);
1099 // Show the ad if this is the free flavor.
1100 if (BuildConfig.FLAVOR.contentEquals("free")) {
1101 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1102 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1108 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1109 // Show the file chooser if the device is running API >= 21.
1110 if (Build.VERSION.SDK_INT >= 21) {
1111 // Store the file path callback.
1112 fileChooserCallback = filePathCallback;
1114 // Create an intent to open a chooser based ont the file chooser parameters.
1115 Intent fileChooserIntent = fileChooserParams.createIntent();
1117 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1118 startActivityForResult(fileChooserIntent, 0);
1124 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1125 registerForContextMenu(mainWebView);
1127 // Allow the downloading of files.
1128 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1129 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1130 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1131 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1133 // Store the variables for future use by `onRequestPermissionsResult()`.
1135 downloadContentDisposition = contentDisposition;
1136 downloadContentLength = contentLength;
1138 // Show a dialog if the user has previously denied the permission.
1139 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1140 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1141 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1143 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1144 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1145 } else { // Show the permission request directly.
1146 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1147 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1149 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1150 // Get a handle for the download file alert dialog.
1151 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1153 // Show the download file alert dialog.
1154 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1158 // Allow pinch to zoom.
1159 mainWebView.getSettings().setBuiltInZoomControls(true);
1161 // Hide zoom controls.
1162 mainWebView.getSettings().setDisplayZoomControls(false);
1164 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1165 mainWebView.getSettings().setUseWideViewPort(true);
1167 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1168 mainWebView.getSettings().setLoadWithOverviewMode(true);
1170 // Explicitly disable geolocation.
1171 mainWebView.getSettings().setGeolocationEnabled(false);
1173 // Initialize cookieManager.
1174 cookieManager = CookieManager.getInstance();
1176 // 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).
1177 customHeaders.put("X-Requested-With", "");
1179 // Initialize the default preference values the first time the program is run. `false` keeps this command from resetting any current preferences back to default.
1180 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1182 // Get the intent that started the app.
1183 final Intent launchingIntent = getIntent();
1185 // Extract the launching intent data as `launchingIntentUriData`.
1186 final Uri launchingIntentUriData = launchingIntent.getData();
1188 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1189 if (launchingIntentUriData != null) {
1190 formattedUrlString = launchingIntentUriData.toString();
1193 // Get a handle for the `Runtime`.
1194 privacyBrowserRuntime = Runtime.getRuntime();
1196 // Store the application's private data directory.
1197 privateDataDirectoryString = getApplicationInfo().dataDir;
1198 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1200 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1201 inFullScreenBrowsingMode = false;
1203 // Initialize the privacy settings variables.
1204 javaScriptEnabled = false;
1205 firstPartyCookiesEnabled = false;
1206 thirdPartyCookiesEnabled = false;
1207 domStorageEnabled = false;
1208 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1211 // Initialize the WebView title.
1212 webViewTitle = getString(R.string.no_title);
1214 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1215 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1216 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1217 assert favoriteIconBitmapDrawable != null;
1218 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1220 // If the favorite icon is null, load the default.
1221 if (favoriteIconBitmap == null) {
1222 favoriteIconBitmap = favoriteIconDefaultBitmap;
1225 // Initialize the user agent array adapter and string array.
1226 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1227 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1229 // Apply the app settings from the shared preferences.
1232 // Instantiate the block list helper.
1233 BlockListHelper blockListHelper = new BlockListHelper();
1235 // Initialize the list of resource requests.
1236 resourceRequests = new ArrayList<>();
1238 // Parse the block lists.
1239 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1240 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1241 final ArrayList<List<String[]>> fanboysAnnoyanceList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1242 final ArrayList<List<String[]>> fanboysSocialList = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1243 final ArrayList<List<String[]>> ultraPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/ultraprivacy.txt");
1245 // Store the list versions.
1246 easyListVersion = easyList.get(0).get(0)[0];
1247 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1248 fanboysAnnoyanceVersion = fanboysAnnoyanceList.get(0).get(0)[0];
1249 fanboysSocialVersion = fanboysSocialList.get(0).get(0)[0];
1250 ultraPrivacyVersion = ultraPrivacy.get(0).get(0)[0];
1252 mainWebView.setWebViewClient(new WebViewClient() {
1253 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1254 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1255 @SuppressWarnings("deprecation")
1257 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1258 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1259 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
1260 formattedUrlString = "";
1262 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1263 applyDomainSettings(url, true, false);
1265 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1267 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1268 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1269 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1271 // Parse the url and set it as the data for the intent.
1272 emailIntent.setData(Uri.parse(url));
1274 // Open the email program in a new task instead of as part of Privacy Browser.
1275 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1278 startActivity(emailIntent);
1280 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1282 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1283 // Open the dialer and load the phone number, but wait for the user to place the call.
1284 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1286 // Add the phone number to the intent.
1287 dialIntent.setData(Uri.parse(url));
1289 // Open the dialer in a new task instead of as part of Privacy Browser.
1290 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1293 startActivity(dialIntent);
1295 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1297 } else { // Load a system chooser to select an app that can handle the URL.
1298 // Open an app that can handle the URL.
1299 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1301 // Add the URL to the intent.
1302 genericIntent.setData(Uri.parse(url));
1304 // List all apps that can handle the URL instead of just opening the first one.
1305 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1307 // Open the app in a new task instead of as part of Privacy Browser.
1308 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1310 // Start the app or display a snackbar if no app is available to handle the URL.
1312 startActivity(genericIntent);
1313 } catch (ActivityNotFoundException exception) {
1314 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1317 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1322 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1323 @SuppressWarnings("deprecation")
1325 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1326 // Create an empty web resource response to be used if the resource request is blocked.
1327 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1329 // Reset the whitelist results tracker.
1330 whiteListResultStringArray = null;
1332 // Initialize the third party request tracker.
1333 boolean isThirdPartyRequest = false;
1335 // Initialize the current domain string.
1336 String currentDomain = "";
1338 // Nobody is happy when comparing null strings.
1339 if (!(formattedUrlString == null) && !(url == null)) {
1340 // Get the domain strings to URIs.
1341 Uri currentDomainUri = Uri.parse(formattedUrlString);
1342 Uri requestDomainUri = Uri.parse(url);
1344 // Get the domain host names.
1345 String currentBaseDomain = currentDomainUri.getHost();
1346 String requestBaseDomain = requestDomainUri.getHost();
1348 // Update the current domain variable.
1349 currentDomain = currentBaseDomain;
1351 // Only compare the current base domain and the request base domain if neither is null.
1352 if (!(currentBaseDomain == null) && !(requestBaseDomain == null)) {
1353 // Determine the current base domain.
1354 while (currentBaseDomain.indexOf(".", currentBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1355 // Remove the first subdomain.
1356 currentBaseDomain = currentBaseDomain.substring(currentBaseDomain.indexOf(".") + 1);
1359 // Determine the request base domain.
1360 while (requestBaseDomain.indexOf(".", requestBaseDomain.indexOf(".") + 1) > 0) { // There is at least one subdomain.
1361 // Remove the first subdomain.
1362 requestBaseDomain = requestBaseDomain.substring(requestBaseDomain.indexOf(".") + 1);
1365 // Update the third party request tracker.
1366 isThirdPartyRequest = !currentBaseDomain.equals(requestBaseDomain);
1370 // Block third-party requests if enabled.
1371 if (isThirdPartyRequest && blockAllThirdPartyRequests) {
1372 // Add the request to the log.
1373 resourceRequests.add(new String[]{String.valueOf(REQUEST_THIRD_PARTY), url});
1375 // Return an empty web resource response.
1376 return emptyWebResourceResponse;
1379 // Check UltraPrivacy if it is enabled.
1380 if (ultraPrivacyEnabled) {
1381 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, ultraPrivacy)) {
1382 // The resource request was blocked. Return an empty web resource response.
1383 return emptyWebResourceResponse;
1386 // If the whitelist result is not null, the request has been allowed by UltraPrivacy.
1387 if (whiteListResultStringArray != null) {
1388 // Add a whitelist entry to the resource requests array.
1389 resourceRequests.add(whiteListResultStringArray);
1391 // The resource request has been allowed by UltraPrivacy. `return null` loads the requested resource.
1396 // Check EasyList if it is enabled.
1397 if (easyListEnabled) {
1398 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyList)) {
1399 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1400 whiteListResultStringArray = null;
1402 // The resource request was blocked. Return an empty web resource response.
1403 return emptyWebResourceResponse;
1407 // Check EasyPrivacy if it is enabled.
1408 if (easyPrivacyEnabled) {
1409 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, easyPrivacy)) {
1410 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1411 whiteListResultStringArray = null;
1413 // The resource request was blocked. Return an empty web resource response.
1414 return emptyWebResourceResponse;
1418 // Check Fanboy’s Annoyance List if it is enabled.
1419 if (fanboysAnnoyanceListEnabled) {
1420 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysAnnoyanceList)) {
1421 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1422 whiteListResultStringArray = null;
1424 // The resource request was blocked. Return an empty web resource response.
1425 return emptyWebResourceResponse;
1427 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1428 if (blockListHelper.isBlocked(currentDomain, url, isThirdPartyRequest, fanboysSocialList)) {
1429 // Reset the whitelist results tracker (because otherwise it will sometimes add results to the list due to a race condition).
1430 whiteListResultStringArray = null;
1432 // The resource request was blocked. Return an empty web resource response.
1433 return emptyWebResourceResponse;
1437 // Add the request to the log because it hasn't been processed by any of the previous checks.
1438 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1439 resourceRequests.add(whiteListResultStringArray);
1440 } else { // The request didn't match any blocklist entry. Log it as a defult request.
1441 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1444 // The resource request has not been blocked. `return null` loads the requested resource.
1448 // Handle HTTP authentication requests.
1450 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1451 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1452 httpAuthHandler = handler;
1454 // Display the HTTP authentication dialog.
1455 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1456 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1459 // Update the URL in urlTextBox when the page starts to load.
1461 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1462 // Reset the list of resource requests.
1463 resourceRequests.clear();
1465 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1467 mainWebView.setVisibility(View.INVISIBLE);
1470 // Hide the keyboard. `0` indicates no additional flags.
1471 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1473 // Check to see if Privacy Browser is waiting on Orbot.
1474 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1475 // 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.
1476 formattedUrlString = url;
1478 // Display the formatted URL text.
1479 urlTextBox.setText(formattedUrlString);
1481 // Apply text highlighting to `urlTextBox`.
1484 // Apply any custom domain settings if the URL was loaded by navigating history.
1485 if (navigatingHistory) {
1486 // Reset `navigatingHistory`.
1487 navigatingHistory = false;
1489 // Apply the domain settings.
1490 applyDomainSettings(url, true, false);
1493 // 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.
1494 urlIsLoading = true;
1498 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1500 public void onPageFinished(WebView view, String url) {
1501 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1502 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1503 cookieManager.flush();
1506 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1507 urlIsLoading = false;
1509 // Clear the cache and history if Incognito Mode is enabled.
1510 if (incognitoModeEnabled) {
1511 // Clear the cache. `true` includes disk files.
1512 mainWebView.clearCache(true);
1514 // Clear the back/forward history.
1515 mainWebView.clearHistory();
1517 // Manually delete cache folders.
1519 // Delete the main cache directory.
1520 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1522 // Delete the secondary `Service Worker` cache directory.
1523 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1524 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1525 } catch (IOException e) {
1526 // Do nothing if an error is thrown.
1530 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1531 if (!waitingForOrbot) {
1532 // Check to see if `WebView` has set `url` to be `about:blank`.
1533 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1534 // Set `formattedUrlString` to `""`.
1535 formattedUrlString = "";
1537 urlTextBox.setText(formattedUrlString);
1539 // Request focus for `urlTextBox`.
1540 urlTextBox.requestFocus();
1542 // Display the keyboard.
1543 inputMethodManager.showSoftInput(urlTextBox, 0);
1545 // Apply the domain settings. This clears any settings from the previous domain.
1546 applyDomainSettings(formattedUrlString, true, false);
1547 } else { // `WebView` has loaded a webpage.
1548 // Set `formattedUrlString`.
1549 formattedUrlString = url;
1551 // Only update `urlTextBox` if the user is not typing in it.
1552 if (!urlTextBox.hasFocus()) {
1553 // Display the formatted URL text.
1554 urlTextBox.setText(formattedUrlString);
1556 // Apply text highlighting to `urlTextBox`.
1561 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1562 sslCertificate = mainWebView.getCertificate();
1564 // 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.
1565 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1566 // Initialize the current SSL certificate variables.
1567 String currentWebsiteIssuedToCName = "";
1568 String currentWebsiteIssuedToOName = "";
1569 String currentWebsiteIssuedToUName = "";
1570 String currentWebsiteIssuedByCName = "";
1571 String currentWebsiteIssuedByOName = "";
1572 String currentWebsiteIssuedByUName = "";
1573 Date currentWebsiteSslStartDate = null;
1574 Date currentWebsiteSslEndDate = null;
1577 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1578 if (sslCertificate != null) {
1579 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1580 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1581 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1582 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1583 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1584 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1585 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1586 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1589 // 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`.
1590 String currentWebsiteSslStartDateString = "";
1591 String currentWebsiteSslEndDateString = "";
1592 String pinnedDomainSslStartDateString = "";
1593 String pinnedDomainSslEndDateString = "";
1595 // Convert the `Dates` to `Strings` if they are not `null`.
1596 if (currentWebsiteSslStartDate != null) {
1597 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1600 if (currentWebsiteSslEndDate != null) {
1601 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1604 if (pinnedDomainSslStartDate != null) {
1605 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1608 if (pinnedDomainSslEndDate != null) {
1609 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1612 // Check to see if the pinned SSL certificate matches the current website certificate.
1613 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1614 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1615 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1616 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1617 // The pinned SSL certificate doesn't match the current domain certificate.
1618 //Display the pinned SSL certificate mismatch `AlertDialog`.
1619 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1620 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1626 // Handle SSL Certificate errors.
1628 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1629 // Get the current website SSL certificate.
1630 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1632 // Extract the individual pieces of information from the current website SSL certificate.
1633 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1634 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1635 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1636 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1637 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1638 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1639 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1640 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1642 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1643 if (pinnedDomainSslCertificate &&
1644 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1645 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1646 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1647 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1648 // An SSL certificate is pinned and matches the current domain certificate.
1649 // Proceed to the website without displaying an error.
1651 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1652 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1653 sslErrorHandler = handler;
1655 // Display the SSL error `AlertDialog`.
1656 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1657 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1662 // Load the website if not waiting for Orbot to connect.
1663 if (!waitingForOrbot) {
1664 loadUrl(formattedUrlString);
1669 protected void onNewIntent(Intent intent) {
1670 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1673 // Check to see if the intent contains a new URL.
1674 if (intent.getData() != null) {
1675 // Get the intent data.
1676 final Uri intentUriData = intent.getData();
1678 // Load the website.
1679 loadUrl(intentUriData.toString());
1681 // Close the navigation drawer if it is open.
1682 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1683 drawerLayout.closeDrawer(GravityCompat.START);
1686 // Close the bookmarks drawer if it is open.
1687 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1688 drawerLayout.closeDrawer(GravityCompat.END);
1691 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1692 mainWebView.requestFocus();
1697 public void onRestart() {
1698 // Run the default commands.
1701 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1702 if (proxyThroughOrbot) {
1703 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1704 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1706 // Send the intent to the Orbot package.
1707 orbotIntent.setPackage("org.torproject.android");
1710 sendBroadcast(orbotIntent);
1713 // Apply the app settings if returning from the Settings activity..
1714 if (reapplyAppSettingsOnRestart) {
1715 // Apply the app settings.
1718 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1719 if (reloadOnRestart) {
1720 // Reload `mainWebView`.
1721 mainWebView.reload();
1723 // Reset `reloadOnRestartBoolean`.
1724 reloadOnRestart = false;
1727 // Reset the return from settings flag.
1728 reapplyAppSettingsOnRestart = false;
1731 // Apply the domain settings if returning from the Domains activity.
1732 if (reapplyDomainSettingsOnRestart) {
1733 // Reapply the domain settings.
1734 applyDomainSettings(formattedUrlString, false, true);
1736 // Reset `reapplyDomainSettingsOnRestart`.
1737 reapplyDomainSettingsOnRestart = false;
1740 // Load the URL on restart to apply changes to night mode.
1741 if (loadUrlOnRestart) {
1742 // Load the current `formattedUrlString`.
1743 loadUrl(formattedUrlString);
1745 // Reset `loadUrlOnRestart.
1746 loadUrlOnRestart = false;
1749 // Update the bookmarks drawer if returning from the Bookmarks activity.
1750 if (restartFromBookmarksActivity) {
1751 // Close the bookmarks drawer.
1752 drawerLayout.closeDrawer(GravityCompat.END);
1754 // Reload the bookmarks drawer.
1755 loadBookmarksFolder();
1757 // Reset `restartFromBookmarksActivity`.
1758 restartFromBookmarksActivity = false;
1761 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1762 updatePrivacyIcons(true);
1765 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1767 public void onResume() {
1768 // Run the default commands.
1771 // Resume JavaScript (if enabled).
1772 mainWebView.resumeTimers();
1774 // Resume `mainWebView`.
1775 mainWebView.onResume();
1777 // Resume the adView for the free flavor.
1778 if (BuildConfig.FLAVOR.contentEquals("free")) {
1780 AdHelper.resumeAd(findViewById(R.id.adview));
1783 // Display a message to the user if waiting for Orbot.
1784 if (waitingForOrbot && !orbotStatus.equals("ON")) {
1785 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1786 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
1789 if (displayingFullScreenVideo) {
1790 // Remove the translucent overlays.
1791 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1793 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1794 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1796 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1797 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1798 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1800 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1805 public void onPause() {
1806 // Run the default commands.
1809 // Pause `mainWebView`.
1810 mainWebView.onPause();
1812 // Stop all JavaScript.
1813 mainWebView.pauseTimers();
1815 // Pause the ad or it will continue to consume resources in the background on the free flavor.
1816 if (BuildConfig.FLAVOR.contentEquals("free")) {
1818 AdHelper.pauseAd(findViewById(R.id.adview));
1823 public void onDestroy() {
1824 // Unregister the Orbot status broadcast receiver.
1825 this.unregisterReceiver(orbotStatusBroadcastReceiver);
1827 // Run the default commands.
1832 public boolean onCreateOptionsMenu(Menu menu) {
1833 // Inflate the menu; this adds items to the action bar if it is present.
1834 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1836 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1839 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1840 updatePrivacyIcons(false);
1842 // Get handles for the menu items.
1843 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1844 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1845 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1846 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1847 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1848 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1849 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1851 // Only display third-party cookies if API >= 21
1852 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1854 // Only display the form data menu items if the API < 26.
1855 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1856 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1858 // Only show Ad Consent if this is the free flavor.
1859 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1861 // Get the shared preference values. `this` references the current context.
1862 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1864 // 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.
1865 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1866 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1867 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1868 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1869 } else { //Do not display the additional icons.
1870 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1871 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1872 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1879 public boolean onPrepareOptionsMenu(Menu menu) {
1880 // Get handles for the menu items.
1881 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1882 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1883 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1884 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1885 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1886 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1887 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1888 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1889 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1890 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1891 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1892 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1893 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1894 MenuItem ultraPrivacyMenuItem = menu.findItem(R.id.ultraprivacy);
1895 MenuItem blockAllThirdParyRequestsMenuItem = menu.findItem(R.id.block_all_third_party_requests);
1896 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1897 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1898 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1900 // Set the text for the domain menu item.
1901 if (domainSettingsApplied) {
1902 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1904 addOrEditDomain.setTitle(R.string.add_domain_settings);
1907 // Set the status of the menu item checkboxes.
1908 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1909 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1910 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1911 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
1912 easyListMenuItem.setChecked(easyListEnabled);
1913 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1914 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1915 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1916 ultraPrivacyMenuItem.setChecked(ultraPrivacyEnabled);
1917 blockAllThirdParyRequestsMenuItem.setChecked(blockAllThirdPartyRequests);
1918 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1919 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1921 // Enable third-party cookies if first-party cookies are enabled.
1922 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1924 // Enable DOM Storage if JavaScript is enabled.
1925 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1927 // Enable Clear Cookies if there are any.
1928 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1930 // Get a count of the number of files in the Local Storage directory.
1931 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1932 int localStorageDirectoryNumberOfFiles = 0;
1933 if (localStorageDirectory.exists()) {
1934 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1937 // Get a count of the number of files in the IndexedDB directory.
1938 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1939 int indexedDBDirectoryNumberOfFiles = 0;
1940 if (indexedDBDirectory.exists()) {
1941 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1944 // Enable Clear DOM Storage if there is any.
1945 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1947 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1948 if (Build.VERSION.SDK_INT < 26) {
1949 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1950 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1952 // Disable clear form data because it is not supported on current version of Android.
1953 clearFormDataMenuItem.setEnabled(false);
1956 // Enable Clear Data if any of the submenu items are enabled.
1957 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1959 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
1960 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1962 // Initialize font size variables.
1963 int fontSize = mainWebView.getSettings().getTextZoom();
1964 String fontSizeTitle;
1965 MenuItem selectedFontSizeMenuItem;
1967 // Prepare the font size title and current size menu item.
1970 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1971 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1975 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1976 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1980 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1981 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1985 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1986 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1990 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1991 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1995 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1996 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2000 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2001 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2005 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2006 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2010 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2011 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2015 // Set the font size title and select the current size menu item.
2016 fontSizeMenuItem.setTitle(fontSizeTitle);
2017 selectedFontSizeMenuItem.setChecked(true);
2019 // Run all the other default commands.
2020 super.onPrepareOptionsMenu(menu);
2022 // Display the menu.
2027 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2028 @SuppressLint("SetJavaScriptEnabled")
2029 // removeAllCookies is deprecated, but it is required for API < 21.
2030 @SuppressWarnings("deprecation")
2031 public boolean onOptionsItemSelected(MenuItem menuItem) {
2032 // Get the selected menu item ID.
2033 int menuItemId = menuItem.getItemId();
2035 // Set the commands that relate to the menu entries.
2036 switch (menuItemId) {
2037 case R.id.toggle_javascript:
2038 // Switch the status of javaScriptEnabled.
2039 javaScriptEnabled = !javaScriptEnabled;
2041 // Apply the new JavaScript status.
2042 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2044 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2045 updatePrivacyIcons(true);
2047 // Display a `Snackbar`.
2048 if (javaScriptEnabled) { // JavaScrip is enabled.
2049 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2050 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2051 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2052 } else { // Privacy mode.
2053 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2056 // Reload the WebView.
2057 mainWebView.reload();
2060 case R.id.add_or_edit_domain:
2061 if (domainSettingsApplied) { // Edit the current domain settings.
2062 // Reapply the domain settings on returning to `MainWebViewActivity`.
2063 reapplyDomainSettingsOnRestart = true;
2064 currentDomainName = "";
2066 // Create an intent to launch the domains activity.
2067 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2069 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
2070 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
2071 domainsIntent.putExtra("closeOnBack", true);
2074 startActivity(domainsIntent);
2075 } else { // Add a new domain.
2076 // Apply the new domain settings on returning to `MainWebViewActivity`.
2077 reapplyDomainSettingsOnRestart = true;
2078 currentDomainName = "";
2080 // Get the current domain
2081 Uri currentUri = Uri.parse(formattedUrlString);
2082 String currentDomain = currentUri.getHost();
2084 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2085 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2087 // Create the domain and store the database ID.
2088 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
2090 // Create an intent to launch the domains activity.
2091 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2093 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
2094 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
2095 domainsIntent.putExtra("closeOnBack", true);
2098 startActivity(domainsIntent);
2102 case R.id.toggle_first_party_cookies:
2103 // Switch the status of firstPartyCookiesEnabled.
2104 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2106 // Update the menu checkbox.
2107 menuItem.setChecked(firstPartyCookiesEnabled);
2109 // Apply the new cookie status.
2110 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2112 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2113 updatePrivacyIcons(true);
2115 // Display a `Snackbar`.
2116 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2117 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2118 } else if (javaScriptEnabled) { // JavaScript is still enabled.
2119 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2120 } else { // Privacy mode.
2121 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2124 // Reload the WebView.
2125 mainWebView.reload();
2128 case R.id.toggle_third_party_cookies:
2129 if (Build.VERSION.SDK_INT >= 21) {
2130 // Switch the status of thirdPartyCookiesEnabled.
2131 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2133 // Update the menu checkbox.
2134 menuItem.setChecked(thirdPartyCookiesEnabled);
2136 // Apply the new cookie status.
2137 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2139 // Display a `Snackbar`.
2140 if (thirdPartyCookiesEnabled) {
2141 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2143 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2146 // Reload the WebView.
2147 mainWebView.reload();
2148 } // Else do nothing because SDK < 21.
2151 case R.id.toggle_dom_storage:
2152 // Switch the status of domStorageEnabled.
2153 domStorageEnabled = !domStorageEnabled;
2155 // Update the menu checkbox.
2156 menuItem.setChecked(domStorageEnabled);
2158 // Apply the new DOM Storage status.
2159 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2161 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2162 updatePrivacyIcons(true);
2164 // Display a `Snackbar`.
2165 if (domStorageEnabled) {
2166 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2168 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2171 // Reload the WebView.
2172 mainWebView.reload();
2175 // Form data can be removed once the minimum API >= 26.
2176 case R.id.toggle_save_form_data:
2177 // Switch the status of saveFormDataEnabled.
2178 saveFormDataEnabled = !saveFormDataEnabled;
2180 // Update the menu checkbox.
2181 menuItem.setChecked(saveFormDataEnabled);
2183 // Apply the new form data status.
2184 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2186 // Display a `Snackbar`.
2187 if (saveFormDataEnabled) {
2188 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2190 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2193 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2194 updatePrivacyIcons(true);
2196 // Reload the WebView.
2197 mainWebView.reload();
2200 case R.id.clear_cookies:
2201 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2202 .setAction(R.string.undo, v -> {
2203 // Do nothing because everything will be handled by `onDismissed()` below.
2205 .addCallback(new Snackbar.Callback() {
2207 public void onDismissed(Snackbar snackbar, int event) {
2209 // The user pushed the `Undo` button.
2210 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2214 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2216 // `cookieManager.removeAllCookie()` varies by SDK.
2217 if (Build.VERSION.SDK_INT < 21) {
2218 cookieManager.removeAllCookie();
2220 // `null` indicates no callback.
2221 cookieManager.removeAllCookies(null);
2229 case R.id.clear_dom_storage:
2230 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2231 .setAction(R.string.undo, v -> {
2232 // Do nothing because everything will be handled by `onDismissed()` below.
2234 .addCallback(new Snackbar.Callback() {
2236 public void onDismissed(Snackbar snackbar, int event) {
2238 // The user pushed the `Undo` button.
2239 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2243 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2245 // Delete the DOM Storage.
2246 WebStorage webStorage = WebStorage.getInstance();
2247 webStorage.deleteAllData();
2249 // Manually delete the DOM storage files and directories.
2251 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2252 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2254 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2255 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2256 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2257 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2258 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2259 } catch (IOException e) {
2260 // Do nothing if an error is thrown.
2268 // Form data can be remove once the minimum API >= 26.
2269 case R.id.clear_form_data:
2270 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2271 .setAction(R.string.undo, v -> {
2272 // Do nothing because everything will be handled by `onDismissed()` below.
2274 .addCallback(new Snackbar.Callback() {
2276 public void onDismissed(Snackbar snackbar, int event) {
2278 // The user pushed the `Undo` button.
2279 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2283 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2285 // Delete the form data.
2286 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2287 mainWebViewDatabase.clearFormData();
2294 case R.id.font_size_twenty_five_percent:
2295 mainWebView.getSettings().setTextZoom(25);
2298 case R.id.font_size_fifty_percent:
2299 mainWebView.getSettings().setTextZoom(50);
2302 case R.id.font_size_seventy_five_percent:
2303 mainWebView.getSettings().setTextZoom(75);
2306 case R.id.font_size_one_hundred_percent:
2307 mainWebView.getSettings().setTextZoom(100);
2310 case R.id.font_size_one_hundred_twenty_five_percent:
2311 mainWebView.getSettings().setTextZoom(125);
2314 case R.id.font_size_one_hundred_fifty_percent:
2315 mainWebView.getSettings().setTextZoom(150);
2318 case R.id.font_size_one_hundred_seventy_five_percent:
2319 mainWebView.getSettings().setTextZoom(175);
2322 case R.id.font_size_two_hundred_percent:
2323 mainWebView.getSettings().setTextZoom(200);
2326 case R.id.swipe_to_refresh:
2327 // Toggle swipe to refresh.
2328 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2331 case R.id.display_images:
2332 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2333 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2334 mainWebView.reload();
2335 } else { // Images are not currently loaded automatically.
2336 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2339 // Set `onTheFlyDisplayImagesSet`.
2340 onTheFlyDisplayImagesSet = true;
2343 case R.id.view_source:
2344 // Launch the View Source activity.
2345 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2346 startActivity(viewSourceIntent);
2350 // Toggle the EasyList status.
2351 easyListEnabled = !easyListEnabled;
2353 // Update the menu checkbox.
2354 menuItem.setChecked(easyListEnabled);
2356 // Reload the main WebView.
2357 mainWebView.reload();
2360 case R.id.easyprivacy:
2361 // Toggle the EasyPrivacy status.
2362 easyPrivacyEnabled = !easyPrivacyEnabled;
2364 // Update the menu checkbox.
2365 menuItem.setChecked(easyPrivacyEnabled);
2367 // Reload the main WebView.
2368 mainWebView.reload();
2371 case R.id.fanboys_annoyance_list:
2372 // Toggle Fanboy's Annoyance List status.
2373 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2375 // Update the menu checkbox.
2376 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2378 // Update the staus of Fanboy's Social Blocking List.
2379 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2380 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2382 // Reload the main WebView.
2383 mainWebView.reload();
2386 case R.id.fanboys_social_blocking_list:
2387 // Toggle Fanboy's Social Blocking List status.
2388 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2390 // Update the menu checkbox.
2391 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2393 // Reload the main WebView.
2394 mainWebView.reload();
2397 case R.id.ultraprivacy:
2398 // Toggle the UltraPrivacy status.
2399 ultraPrivacyEnabled = !ultraPrivacyEnabled;
2401 // Update the menu checkbox.
2402 menuItem.setChecked(ultraPrivacyEnabled);
2404 // Reload the main WebView.
2405 mainWebView.reload();
2408 case R.id.block_all_third_party_requests:
2409 //Toggle the third-party requests blocker status.
2410 blockAllThirdPartyRequests = !blockAllThirdPartyRequests;
2412 // Update the menu checkbox.
2413 menuItem.setChecked(blockAllThirdPartyRequests);
2415 // Reload the main WebView.
2416 mainWebView.reload();
2420 // Setup the share string.
2421 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2423 // Create the share intent.
2424 Intent shareIntent = new Intent();
2425 shareIntent.setAction(Intent.ACTION_SEND);
2426 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2427 shareIntent.setType("text/plain");
2430 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2433 case R.id.find_on_page:
2434 // Hide the URL app bar.
2435 supportAppBar.setVisibility(View.GONE);
2437 // Show the Find on Page `RelativeLayout`.
2438 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2440 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2441 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2442 findOnPageEditText.postDelayed(() -> {
2443 // Set the focus on `findOnPageEditText`.
2444 findOnPageEditText.requestFocus();
2446 // Display the keyboard. `0` sets no input flags.
2447 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2452 // Get a `PrintManager` instance.
2453 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2455 // Convert `mainWebView` to `printDocumentAdapter`.
2456 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2458 // Remove the lint error below that `printManager` might be `null`.
2459 assert printManager != null;
2461 // Print the document. The print attributes are `null`.
2462 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2465 case R.id.add_to_homescreen:
2466 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2467 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2468 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2470 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2474 mainWebView.reload();
2477 case R.id.ad_consent:
2478 // Display the ad consent dialog.
2479 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2480 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2484 // Don't consume the event.
2485 return super.onOptionsItemSelected(menuItem);
2489 // removeAllCookies is deprecated, but it is required for API < 21.
2490 @SuppressWarnings("deprecation")
2492 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2493 int menuItemId = menuItem.getItemId();
2495 switch (menuItemId) {
2501 if (mainWebView.canGoBack()) {
2502 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2503 formattedUrlString = "";
2505 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2506 navigatingHistory = true;
2508 // Load the previous website in the history.
2509 mainWebView.goBack();
2514 if (mainWebView.canGoForward()) {
2515 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
2516 formattedUrlString = "";
2518 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2519 navigatingHistory = true;
2521 // Load the next website in the history.
2522 mainWebView.goForward();
2527 // Get the `WebBackForwardList`.
2528 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2530 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2531 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2532 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2536 // Launch the requests activity.
2537 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2538 startActivity(requestsIntent);
2541 case R.id.downloads:
2542 // Launch the system Download Manager.
2543 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2545 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2546 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2548 startActivity(downloadManagerIntent);
2552 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2553 reapplyDomainSettingsOnRestart = true;
2554 currentDomainName = "";
2556 // Launch the domains activity.
2557 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2558 startActivity(domainsIntent);
2562 // Set the flag to reapply app settings on restart when returning from Settings.
2563 reapplyAppSettingsOnRestart = true;
2565 // Set the flag to reapply the domain settings on restart when returning from Settings.
2566 reapplyDomainSettingsOnRestart = true;
2567 currentDomainName = "";
2569 // Launch the settings activity.
2570 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2571 startActivity(settingsIntent);
2575 // Launch `GuideActivity`.
2576 Intent guideIntent = new Intent(this, GuideActivity.class);
2577 startActivity(guideIntent);
2581 // Launch `AboutActivity`.
2582 Intent aboutIntent = new Intent(this, AboutActivity.class);
2583 startActivity(aboutIntent);
2586 case R.id.clearAndExit:
2587 // Get a handle for `sharedPreferences`. `this` references the current context.
2588 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2590 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2593 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2594 // The command to remove cookies changed slightly in API 21.
2595 if (Build.VERSION.SDK_INT >= 21) {
2596 cookieManager.removeAllCookies(null);
2598 cookieManager.removeAllCookie();
2601 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2603 // We have to use two commands because `Runtime.exec()` does not like `*`.
2604 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2605 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2606 } catch (IOException e) {
2607 // Do nothing if an error is thrown.
2611 // Clear DOM storage.
2612 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2613 // Ask `WebStorage` to clear the DOM storage.
2614 WebStorage webStorage = WebStorage.getInstance();
2615 webStorage.deleteAllData();
2617 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2619 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2620 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2622 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2623 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2624 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2625 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2626 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2627 } catch (IOException e) {
2628 // Do nothing if an error is thrown.
2632 // Clear form data if the API < 26.
2633 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2634 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2635 webViewDatabase.clearFormData();
2637 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2639 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2640 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2641 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2642 } catch (IOException e) {
2643 // Do nothing if an error is thrown.
2648 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2649 // `true` includes disk files.
2650 mainWebView.clearCache(true);
2652 // Manually delete the cache directories.
2654 // Delete the main cache directory.
2655 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2657 // Delete the secondary `Service Worker` cache directory.
2658 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2659 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2660 } catch (IOException e) {
2661 // Do nothing if an error is thrown.
2665 // Clear SSL certificate preferences.
2666 mainWebView.clearSslPreferences();
2668 // Clear the back/forward history.
2669 mainWebView.clearHistory();
2671 // Clear `formattedUrlString`.
2672 formattedUrlString = null;
2674 // Clear `customHeaders`.
2675 customHeaders.clear();
2677 // Detach all views from `mainWebViewRelativeLayout`.
2678 mainWebViewRelativeLayout.removeAllViews();
2680 // Destroy the internal state of `mainWebView`.
2681 mainWebView.destroy();
2683 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2684 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2685 if (clearEverything) {
2687 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2688 } catch (IOException e) {
2689 // Do nothing if an error is thrown.
2693 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2694 if (Build.VERSION.SDK_INT >= 21) {
2695 finishAndRemoveTask();
2700 // Remove the terminated program from RAM. The status code is `0`.
2705 // Close the navigation drawer.
2706 drawerLayout.closeDrawer(GravityCompat.START);
2711 public void onPostCreate(Bundle savedInstanceState) {
2712 super.onPostCreate(savedInstanceState);
2714 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2715 drawerToggle.syncState();
2719 public void onConfigurationChanged(Configuration newConfig) {
2720 super.onConfigurationChanged(newConfig);
2722 // Reload the ad for the free flavor if we not in full screen mode.
2723 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2724 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2725 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2728 // `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:
2729 // https://code.google.com/p/android/issues/detail?id=20493#c8
2730 // ActivityCompat.invalidateOptionsMenu(this);
2734 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2735 // Store the `HitTestResult`.
2736 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2739 final String imageUrl;
2740 final String linkUrl;
2742 // Get a handle for the `ClipboardManager`.
2743 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2745 // Remove the lint errors below that `clipboardManager` might be `null`.
2746 assert clipboardManager != null;
2748 switch (hitTestResult.getType()) {
2749 // `SRC_ANCHOR_TYPE` is a link.
2750 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2751 // Get the target URL.
2752 linkUrl = hitTestResult.getExtra();
2754 // Set the target URL as the title of the `ContextMenu`.
2755 menu.setHeaderTitle(linkUrl);
2757 // Add a Load URL entry.
2758 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2763 // Add a Copy URL entry.
2764 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2765 // Save the link URL in a `ClipData`.
2766 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2768 // Set the `ClipData` as the clipboard's primary clip.
2769 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2773 // Add a Download URL entry.
2774 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2775 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2776 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2777 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2779 // Store the variables for future use by `onRequestPermissionsResult()`.
2780 downloadUrl = linkUrl;
2781 downloadContentDisposition = "none";
2782 downloadContentLength = -1;
2784 // Show a dialog if the user has previously denied the permission.
2785 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2786 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2787 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2789 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2790 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2791 } else { // Show the permission request directly.
2792 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2793 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2795 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2796 // Get a handle for the download file alert dialog.
2797 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2799 // Show the download file alert dialog.
2800 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2805 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2806 menu.add(R.string.cancel);
2809 case WebView.HitTestResult.EMAIL_TYPE:
2810 // Get the target URL.
2811 linkUrl = hitTestResult.getExtra();
2813 // Set the target URL as the title of the `ContextMenu`.
2814 menu.setHeaderTitle(linkUrl);
2816 // Add a `Write Email` entry.
2817 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2818 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2819 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2821 // Parse the url and set it as the data for the `Intent`.
2822 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2824 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2825 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2828 startActivity(emailIntent);
2832 // Add a `Copy Email Address` entry.
2833 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2834 // Save the email address in a `ClipData`.
2835 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2837 // Set the `ClipData` as the clipboard's primary clip.
2838 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2842 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2843 menu.add(R.string.cancel);
2846 // `IMAGE_TYPE` is an image.
2847 case WebView.HitTestResult.IMAGE_TYPE:
2848 // Get the image URL.
2849 imageUrl = hitTestResult.getExtra();
2851 // Set the image URL as the title of the `ContextMenu`.
2852 menu.setHeaderTitle(imageUrl);
2854 // Add a `View Image` entry.
2855 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2860 // Add a `Download Image` entry.
2861 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2862 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2863 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2864 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2866 // Store the image URL for use by `onRequestPermissionResult()`.
2867 downloadImageUrl = imageUrl;
2869 // Show a dialog if the user has previously denied the permission.
2870 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2871 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2872 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2874 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2875 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2876 } else { // Show the permission request directly.
2877 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2878 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2880 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2881 // Get a handle for the download image alert dialog.
2882 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2884 // Show the download image alert dialog.
2885 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2890 // Add a `Copy URL` entry.
2891 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2892 // Save the image URL in a `ClipData`.
2893 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2895 // Set the `ClipData` as the clipboard's primary clip.
2896 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2900 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2901 menu.add(R.string.cancel);
2905 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2906 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2907 // Get the image URL.
2908 imageUrl = hitTestResult.getExtra();
2910 // Set the image URL as the title of the `ContextMenu`.
2911 menu.setHeaderTitle(imageUrl);
2913 // Add a `View Image` entry.
2914 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2919 // Add a `Download Image` entry.
2920 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2921 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2922 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2923 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2925 // Store the image URL for use by `onRequestPermissionResult()`.
2926 downloadImageUrl = imageUrl;
2928 // Show a dialog if the user has previously denied the permission.
2929 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2930 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2931 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2933 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2934 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2935 } else { // Show the permission request directly.
2936 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2937 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2939 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2940 // Get a handle for the download image alert dialog.
2941 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2943 // Show the download image alert dialog.
2944 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2949 // Add a `Copy URL` entry.
2950 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2951 // Save the image URL in a `ClipData`.
2952 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2954 // Set the `ClipData` as the clipboard's primary clip.
2955 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2959 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2960 menu.add(R.string.cancel);
2966 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2967 // Get the `EditTexts` from the `dialogFragment`.
2968 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2969 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2971 // Extract the strings from the `EditTexts`.
2972 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2973 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2975 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2976 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2977 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2978 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2980 // Display the new bookmark below the current items in the (0 indexed) list.
2981 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2983 // Create the bookmark.
2984 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2986 // Update `bookmarksCursor` with the current contents of this folder.
2987 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2989 // Update the `ListView`.
2990 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2992 // Scroll to the new bookmark.
2993 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2997 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2998 // Get handles for the views in `dialogFragment`.
2999 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3000 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3001 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3003 // Get new folder name string.
3004 String folderNameString = createFolderNameEditText.getText().toString();
3006 // Get the new folder icon `Bitmap`.
3007 Bitmap folderIconBitmap;
3008 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3009 // Get the default folder icon and convert it to a `Bitmap`.
3010 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3011 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3012 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3013 } else { // Use the `WebView` favorite icon.
3014 folderIconBitmap = favoriteIconBitmap;
3017 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3018 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3019 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3020 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3022 // Move all the bookmarks down one in the display order.
3023 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3024 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3025 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3028 // Create the folder, which will be placed at the top of the `ListView`.
3029 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3031 // Update `bookmarksCursor` with the current contents of this folder.
3032 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3034 // Update the `ListView`.
3035 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3037 // Scroll to the new folder.
3038 bookmarksListView.setSelection(0);
3042 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3043 // Get the shortcut name.
3044 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3045 String shortcutNameString = shortcutNameEditText.getText().toString();
3047 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3048 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3050 // Setup the shortcut intent.
3051 Intent shortcutIntent = new Intent();
3052 shortcutIntent.setAction(Intent.ACTION_VIEW);
3053 shortcutIntent.setData(Uri.parse(formattedUrlString));
3055 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3056 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3058 // Add the required fields to the shortcut info builder.
3059 shortcutInfoBuilder.setIcon(favoriteIcon);
3060 shortcutInfoBuilder.setIntent(shortcutIntent);
3061 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3063 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3064 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3068 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
3069 switch (downloadType) {
3070 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
3071 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
3072 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
3075 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
3076 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
3077 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
3083 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
3084 switch (requestCode) {
3085 case DOWNLOAD_FILE_REQUEST_CODE:
3086 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3087 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
3089 // On API 23, displaying the fragment must be delayed or the app will crash.
3090 if (Build.VERSION.SDK_INT == 23) {
3091 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3093 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3096 // Reset the download variables.
3098 downloadContentDisposition = "";
3099 downloadContentLength = 0;
3102 case DOWNLOAD_IMAGE_REQUEST_CODE:
3103 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
3104 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
3106 // On API 23, displaying the fragment must be delayed or the app will crash.
3107 if (Build.VERSION.SDK_INT == 23) {
3108 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
3110 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3113 // Reset the image URL variable.
3114 downloadImageUrl = "";
3120 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3121 // Download the image if it has an HTTP or HTTPS URI.
3122 if (imageUrl.startsWith("http")) {
3123 // Get a handle for the system `DOWNLOAD_SERVICE`.
3124 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3126 // Parse `imageUrl`.
3127 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3129 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3130 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3131 if (firstPartyCookiesEnabled) {
3132 // Get the cookies for `imageUrl`.
3133 String cookies = cookieManager.getCookie(imageUrl);
3135 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3136 downloadRequest.addRequestHeader("Cookie", cookies);
3139 // Get the file name from the dialog fragment.
3140 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3141 String imageName = downloadImageNameEditText.getText().toString();
3143 // Specify the download location.
3144 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3145 // Download to the public download directory.
3146 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
3147 } else { // External write permission denied.
3148 // Download to the app's external download directory.
3149 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
3152 // Allow `MediaScanner` to index the download if it is a media file.
3153 downloadRequest.allowScanningByMediaScanner();
3155 // Add the URL as the description for the download.
3156 downloadRequest.setDescription(imageUrl);
3158 // Show the download notification after the download is completed.
3159 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3161 // Remove the lint warning below that `downloadManager` might be `null`.
3162 assert downloadManager != null;
3164 // Initiate the download.
3165 downloadManager.enqueue(downloadRequest);
3166 } else { // The image is not an HTTP or HTTPS URI.
3167 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3172 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3173 // Download the file if it has an HTTP or HTTPS URI.
3174 if (downloadUrl.startsWith("http")) {
3175 // Get a handle for the system `DOWNLOAD_SERVICE`.
3176 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3178 // Parse `downloadUrl`.
3179 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3181 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3182 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3183 if (firstPartyCookiesEnabled) {
3184 // Get the cookies for `downloadUrl`.
3185 String cookies = cookieManager.getCookie(downloadUrl);
3187 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3188 downloadRequest.addRequestHeader("Cookie", cookies);
3191 // Get the file name from the dialog fragment.
3192 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3193 String fileName = downloadFileNameEditText.getText().toString();
3195 // Specify the download location.
3196 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
3197 // Download to the public download directory.
3198 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
3199 } else { // External write permission denied.
3200 // Download to the app's external download directory.
3201 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
3204 // Allow `MediaScanner` to index the download if it is a media file.
3205 downloadRequest.allowScanningByMediaScanner();
3207 // Add the URL as the description for the download.
3208 downloadRequest.setDescription(downloadUrl);
3210 // Show the download notification after the download is completed.
3211 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3213 // Remove the lint warning below that `downloadManager` might be `null`.
3214 assert downloadManager != null;
3216 // Initiate the download.
3217 downloadManager.enqueue(downloadRequest);
3218 } else { // The download is not an HTTP or HTTPS URI.
3219 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3224 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3225 // Get handles for the views from `dialogFragment`.
3226 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3227 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3228 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3230 // Store the bookmark strings.
3231 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3232 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3234 // Update the bookmark.
3235 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3236 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3237 } else { // Update the bookmark using the `WebView` favorite icon.
3238 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3239 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3240 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3241 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3243 // Update the bookmark and the favorite icon.
3244 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3247 // Update `bookmarksCursor` with the current contents of this folder.
3248 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3250 // Update the `ListView`.
3251 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3255 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3256 // Get handles for the views from `dialogFragment`.
3257 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3258 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3259 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3260 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3262 // Get the new folder name.
3263 String newFolderNameString = editFolderNameEditText.getText().toString();
3265 // Check if the favorite icon has changed.
3266 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3267 // Update the name in the database.
3268 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3269 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3270 // Get the new folder icon `Bitmap`.
3271 Bitmap folderIconBitmap;
3272 if (defaultFolderIconRadioButton.isChecked()) {
3273 // Get the default folder icon and convert it to a `Bitmap`.
3274 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3275 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3276 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3277 } else { // Use the `WebView` favorite icon.
3278 folderIconBitmap = favoriteIconBitmap;
3281 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3282 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3283 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3284 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3286 // Update the folder icon in the database.
3287 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3288 } else { // The folder icon and the name have changed.
3289 // Get the new folder icon `Bitmap`.
3290 Bitmap folderIconBitmap;
3291 if (defaultFolderIconRadioButton.isChecked()) {
3292 // Get the default folder icon and convert it to a `Bitmap`.
3293 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3294 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3295 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3296 } else { // Use the `WebView` favorite icon.
3297 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3300 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3301 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3302 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3303 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3305 // Update the folder name and icon in the database.
3306 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3309 // Update `bookmarksCursor` with the current contents of this folder.
3310 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3312 // Update the `ListView`.
3313 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3317 public void onHttpAuthenticationCancel() {
3318 // Cancel the `HttpAuthHandler`.
3319 httpAuthHandler.cancel();
3323 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3324 // Get handles for the `EditTexts`.
3325 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3326 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3328 // Proceed with the HTTP authentication.
3329 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3332 public void viewSslCertificate(View view) {
3333 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3334 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3335 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3339 public void onSslErrorCancel() {
3340 sslErrorHandler.cancel();
3344 public void onSslErrorProceed() {
3345 sslErrorHandler.proceed();
3349 public void onSslMismatchBack() {
3350 if (mainWebView.canGoBack()) { // There is a back page in the history.
3351 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3352 formattedUrlString = "";
3354 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3355 navigatingHistory = true;
3358 mainWebView.goBack();
3359 } else { // There are no pages to go back to.
3360 // Load a blank page
3366 public void onSslMismatchProceed() {
3367 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3368 ignorePinnedSslCertificate = true;
3372 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3373 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3374 formattedUrlString = "";
3376 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3377 navigatingHistory = true;
3379 // Load the history entry.
3380 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3384 public void onClearHistory() {
3385 // Clear the history.
3386 mainWebView.clearHistory();
3389 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3391 public void onBackPressed() {
3392 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3393 // Close the navigation drawer.
3394 drawerLayout.closeDrawer(GravityCompat.START);
3395 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3396 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3397 // close the bookmarks drawer.
3398 drawerLayout.closeDrawer(GravityCompat.END);
3399 } else { // A subfolder is displayed.
3400 // Place the former parent folder in `currentFolder`.
3401 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3403 // Load the new folder.
3404 loadBookmarksFolder();
3407 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3408 // Reset the formatted URL string so the page will load correctly if blocking of third-party requests is enabled.
3409 formattedUrlString = "";
3411 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3412 navigatingHistory = true;
3415 mainWebView.goBack();
3416 } else { // There isn't anything to do in Privacy Browser.
3417 // Pass `onBackPressed()` to the system.
3418 super.onBackPressed();
3422 // 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.
3424 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3425 // File uploads only work on API >= 21.
3426 if (Build.VERSION.SDK_INT >= 21) {
3427 // Pass the file to the WebView.
3428 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3432 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3433 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3434 String unformattedUrlString = urlTextBox.getText().toString().trim();
3436 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3437 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3438 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3439 if (!unformattedUrlString.startsWith("http")) {
3440 unformattedUrlString = "http://" + unformattedUrlString;
3443 // Initialize `unformattedUrl`.
3444 URL unformattedUrl = null;
3446 // 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.
3448 unformattedUrl = new URL(unformattedUrlString);
3449 } catch (MalformedURLException e) {
3450 e.printStackTrace();
3453 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3454 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3455 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3456 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3457 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3458 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3461 Uri.Builder formattedUri = new Uri.Builder();
3462 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3464 // Decode `formattedUri` as a `String` in `UTF-8`.
3465 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3466 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3467 // Load a blank string.
3468 formattedUrlString = "";
3469 } else { // Search for the contents of the URL box.
3470 // Sanitize the search input and convert it to a search.
3471 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3473 // Add the base search URL.
3474 formattedUrlString = searchURL + encodedUrlString;
3477 // 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.
3478 urlTextBox.clearFocus();
3481 loadUrl(formattedUrlString);
3484 private void loadUrl(String url) {// Apply any custom domain settings.
3485 // Set the URL as the formatted URL string so that checking third-party requests works correctly.
3486 formattedUrlString = url;
3488 // Apply the domain settings.
3489 applyDomainSettings(url, true, false);
3491 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3492 urlIsLoading = true;
3495 mainWebView.loadUrl(url, customHeaders);
3498 public void findPreviousOnPage(View view) {
3499 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3500 mainWebView.findNext(false);
3503 public void findNextOnPage(View view) {
3504 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3505 mainWebView.findNext(true);
3508 public void closeFindOnPage(View view) {
3509 // Delete the contents of `find_on_page_edittext`.
3510 findOnPageEditText.setText(null);
3512 // Clear the highlighted phrases.
3513 mainWebView.clearMatches();
3515 // Hide the Find on Page `RelativeLayout`.
3516 findOnPageLinearLayout.setVisibility(View.GONE);
3518 // Show the URL app bar.
3519 supportAppBar.setVisibility(View.VISIBLE);
3521 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3522 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3525 private void applyAppSettings() {
3526 // Get a handle for the shared preferences.
3527 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3529 // Store the values from the shared preferences in variables.
3530 String homepageString = sharedPreferences.getString("homepage", "https://searx.me/");
3531 String torHomepageString = sharedPreferences.getString("tor_homepage", "http://ulrn6sryqaifefld.onion/");
3532 String torSearchString = sharedPreferences.getString("tor_search", "http://ulrn6sryqaifefld.onion/?q=");
3533 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3534 String searchString = sharedPreferences.getString("search", "https://searx.me/?q=");
3535 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3536 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3537 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3538 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3539 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3540 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3541 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3542 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3544 // Set the homepage, search, and proxy options.
3545 if (proxyThroughOrbot) { // Set the Tor options.
3546 // Set `torHomepageString` as `homepage`.
3547 homepage = torHomepageString;
3549 // If formattedUrlString is null assign the homepage to it.
3550 if (formattedUrlString == null) {
3551 formattedUrlString = homepage;
3554 // Set the search URL.
3555 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3556 searchURL = torSearchCustomURLString;
3557 } else { // Use the string from the pre-built list.
3558 searchURL = torSearchString;
3561 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3562 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3564 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3566 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3568 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3571 // Display a message to the user if waiting for Orbot.
3572 if (!orbotStatus.equals("ON")) {
3573 // Set `waitingForOrbot`.
3574 waitingForOrbot = true;
3576 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3577 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3579 } else { // Set the non-Tor options.
3580 // Set `homepageString` as `homepage`.
3581 homepage = homepageString;
3583 // If formattedUrlString is null assign the homepage to it.
3584 if (formattedUrlString == null) {
3585 formattedUrlString = homepage;
3588 // Set the search URL.
3589 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3590 searchURL = searchCustomURLString;
3591 } else { // Use the string from the pre-built list.
3592 searchURL = searchString;
3595 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3596 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3598 // Set the default `appBar` background. `this` refers to the context.
3600 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3602 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3605 // Reset `waitingForOrbot.
3606 waitingForOrbot = false;
3609 // Set Do Not Track status.
3610 if (doNotTrackEnabled) {
3611 customHeaders.put("DNT", "1");
3613 customHeaders.remove("DNT");
3616 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3617 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) { // Privacy Browser is currently in full screen browsing mode.
3618 if (hideSystemBarsOnFullscreen) { // Hide everything.
3619 // Remove the translucent navigation setting if it is currently flagged.
3620 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3622 // Remove the translucent status bar overlay.
3623 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3625 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3626 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3628 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3629 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3630 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3632 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3633 } else { // Hide everything except the status and navigation bars.
3634 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3635 rootCoordinatorLayout.setSystemUiVisibility(0);
3637 // Add the translucent status flag if it is unset.
3638 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3640 if (translucentNavigationBarOnFullscreen) {
3641 // Set the navigation bar to be translucent.
3642 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3644 // Set the navigation bar to be black.
3645 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3648 } else { // Privacy Browser is not in full screen browsing mode.
3649 // 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.
3650 inFullScreenBrowsingMode = false;
3652 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3653 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3657 // Show the `BannerAd` in the free flavor.
3658 if (BuildConfig.FLAVOR.contentEquals("free")) {
3659 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3660 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3663 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3664 rootCoordinatorLayout.setSystemUiVisibility(0);
3666 // Remove the translucent navigation bar flag if it is set.
3667 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3669 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3670 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3672 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3673 rootCoordinatorLayout.setFitsSystemWindows(true);
3677 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3678 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3679 @SuppressWarnings("deprecation")
3680 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3681 // Parse the URL into a URI.
3682 Uri uri = Uri.parse(url);
3684 // Extract the domain from `uri`.
3685 String hostName = uri.getHost();
3687 // Initialize `loadingNewDomainName`.
3688 boolean loadingNewDomainName;
3690 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3691 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3692 //noinspection SimplifiableIfStatement
3693 if ((hostName == null) || (currentDomainName == null)) {
3694 loadingNewDomainName = true;
3695 } else { // Determine if `hostName` equals `currentDomainName`.
3696 loadingNewDomainName = !hostName.equals(currentDomainName);
3699 // Strings don't like to be null.
3700 if (hostName == null) {
3704 // 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.
3705 if (loadingNewDomainName) {
3706 // Set the new `hostname` as the `currentDomainName`.
3707 currentDomainName = hostName;
3709 // Reset `ignorePinnedSslCertificate`.
3710 ignorePinnedSslCertificate = false;
3712 // Reset the favorite icon if specified.
3713 if (resetFavoriteIcon) {
3714 favoriteIconBitmap = favoriteIconDefaultBitmap;
3715 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3718 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3719 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3720 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3722 // Get a full cursor from `domainsDatabaseHelper`.
3723 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3725 // Initialize `domainSettingsSet`.
3726 Set<String> domainSettingsSet = new HashSet<>();
3728 // Get the domain name column index.
3729 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3731 // Populate `domainSettingsSet`.
3732 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3733 // Move `domainsCursor` to the current row.
3734 domainNameCursor.moveToPosition(i);
3736 // Store the domain name in `domainSettingsSet`.
3737 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3740 // Close `domainNameCursor.
3741 domainNameCursor.close();
3743 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3744 domainSettingsApplied = false;
3745 String domainNameInDatabase = null;
3747 // Check the hostname.
3748 if (domainSettingsSet.contains(hostName)) {
3749 domainSettingsApplied = true;
3750 domainNameInDatabase = hostName;
3753 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3754 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3755 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3756 // Apply the domain settings.
3757 domainSettingsApplied = true;
3759 // Store the applied domain names as it appears in the database.
3760 domainNameInDatabase = "*." + hostName;
3763 // Strip out the lowest subdomain of of the host name.
3764 hostName = hostName.substring(hostName.indexOf(".") + 1);
3768 // Get a handle for the shared preference.
3769 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3771 // Store the general preference information.
3772 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3773 String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3774 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3775 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3776 nightMode = sharedPreferences.getBoolean("night_mode", false);
3778 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3779 // Get a cursor for the current host and move it to the first position.
3780 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3781 currentHostDomainSettingsCursor.moveToFirst();
3783 // Get the settings from the cursor.
3784 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3785 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3786 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3787 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3788 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3789 // Form data can be removed once the minimum API >= 26.
3790 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3791 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3792 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3793 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3794 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3795 ultraPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_ULTRAPRIVACY)) == 1);
3796 blockAllThirdPartyRequests = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.BLOCK_ALL_THIRD_PARTY_REQUESTS)) == 1);
3797 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3798 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3799 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3800 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3801 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3802 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3803 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3804 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3805 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3806 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3807 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3808 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3810 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3811 switch (nightModeInt) {
3812 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3816 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3821 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3823 javaScriptEnabled = true;
3826 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3827 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3828 pinnedDomainSslStartDate = null;
3830 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3833 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3834 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3835 pinnedDomainSslEndDate = null;
3837 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3840 // Close `currentHostDomainSettingsCursor`.
3841 currentHostDomainSettingsCursor.close();
3843 // Apply the domain settings.
3844 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3845 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3846 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3848 // Apply the form data setting if the API < 26.
3849 if (Build.VERSION.SDK_INT < 26) {
3850 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3853 // Apply the font size.
3854 if (fontSize == 0) { // Apply the default font size.
3855 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3856 } else { // Apply the specified font size.
3857 mainWebView.getSettings().setTextZoom(fontSize);
3860 // Set third-party cookies status if API >= 21.
3861 if (Build.VERSION.SDK_INT >= 21) {
3862 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3865 // 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.
3866 // <https://redmine.stoutner.com/issues/160>
3867 if (!urlIsLoading) {
3868 // Set the user agent.
3869 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3870 // Get the array position of the default user agent name.
3871 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3873 // Set the user agent according to the system default.
3874 switch (defaultUserAgentArrayPosition) {
3875 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3876 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3877 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3880 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3881 // Set the user agent to `""`, which uses the default value.
3882 mainWebView.getSettings().setUserAgentString("");
3885 case SETTINGS_CUSTOM_USER_AGENT:
3886 // Set the custom user agent.
3887 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3891 // Get the user agent string from the user agent data array
3892 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3894 } else { // Set the user agent according to the stored name.
3895 // Get the array position of the user agent name.
3896 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3898 switch (userAgentArrayPosition) {
3899 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3900 mainWebView.getSettings().setUserAgentString(userAgentName);
3903 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3904 // Set the user agent to `""`, which uses the default value.
3905 mainWebView.getSettings().setUserAgentString("");
3909 // Get the user agent string from the user agent data array.
3910 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3914 // Set swipe to refresh.
3915 switch (swipeToRefreshInt) {
3916 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3917 // Set swipe to refresh according to the default.
3918 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3921 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3922 // Enable swipe to refresh.
3923 swipeRefreshLayout.setEnabled(true);
3926 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3927 // Disable swipe to refresh.
3928 swipeRefreshLayout.setEnabled(false);
3931 // Store the applied user agent string, which is used in the View Source activity.
3932 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3935 // 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.
3937 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3939 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3941 } else { // The new URL does not have custom domain settings. Load the defaults.
3942 // Store the values from `sharedPreferences` in variables.
3943 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3944 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3945 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3946 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3947 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false); // Form data can be removed once the minimum API >= 26.
3948 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3949 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3950 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3951 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3952 ultraPrivacyEnabled = sharedPreferences.getBoolean("ultraprivacy", true);
3953 blockAllThirdPartyRequests = sharedPreferences.getBoolean("block_all_third_party_requests", false);
3955 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3957 javaScriptEnabled = true;
3960 // Apply the default settings.
3961 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3962 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3963 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3964 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3965 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3967 // Apply the form data setting if the API < 26.
3968 if (Build.VERSION.SDK_INT < 26) {
3969 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3972 // Reset the pinned SSL certificate information.
3973 domainSettingsDatabaseId = -1;
3974 pinnedDomainSslCertificate = false;
3975 pinnedDomainSslIssuedToCNameString = "";
3976 pinnedDomainSslIssuedToONameString = "";
3977 pinnedDomainSslIssuedToUNameString = "";
3978 pinnedDomainSslIssuedByCNameString = "";
3979 pinnedDomainSslIssuedByONameString = "";
3980 pinnedDomainSslIssuedByUNameString = "";
3981 pinnedDomainSslStartDate = null;
3982 pinnedDomainSslEndDate = null;
3984 // Set third-party cookies status if API >= 21.
3985 if (Build.VERSION.SDK_INT >= 21) {
3986 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3989 // 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.
3990 // <https://redmine.stoutner.com/issues/160>
3991 if (!urlIsLoading) {
3992 // Get the array position of the user agent name.
3993 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3995 // Set the user agent.
3996 switch (userAgentArrayPosition) {
3997 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3998 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3999 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
4002 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
4003 // Set the user agent to `""`, which uses the default value.
4004 mainWebView.getSettings().setUserAgentString("");
4007 case SETTINGS_CUSTOM_USER_AGENT:
4008 // Set the custom user agent.
4009 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4013 // Get the user agent string from the user agent data array
4014 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
4017 // Store the applied user agent string, which is used in the View Source activity.
4018 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4021 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4022 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4025 // Close `domainsDatabaseHelper`.
4026 domainsDatabaseHelper.close();
4028 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
4029 onTheFlyDisplayImagesSet = false;
4030 setDisplayWebpageImages();
4032 // Update the privacy icons, but only if `mainMenu` has already been populated.
4033 if (mainMenu != null) {
4034 updatePrivacyIcons(true);
4038 // Reload the website if returning from the Domains activity.
4039 if (reloadWebsite) {
4040 mainWebView.reload();
4044 private void setDisplayWebpageImages() {
4045 if (!onTheFlyDisplayImagesSet) {
4046 if (domainSettingsApplied) { // Custom domain settings are applied.
4047 switch (displayWebpageImagesInt) {
4048 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4049 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4052 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4053 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4056 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4057 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4060 } else { // Default settings are applied.
4061 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4066 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4067 // Get handles for the menu items.
4068 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4069 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4070 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4071 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
4073 // Update the privacy icon.
4074 if (javaScriptEnabled) { // JavaScript is enabled.
4075 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
4076 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4077 privacyMenuItem.setIcon(R.drawable.warning);
4078 } else { // All the dangerous features are disabled.
4079 privacyMenuItem.setIcon(R.drawable.privacy_mode);
4082 // Update the first-party cookies icon.
4083 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4084 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
4085 } else { // First-party cookies are disabled.
4087 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4089 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
4093 // Update the DOM storage icon.
4094 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4095 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
4096 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4098 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4100 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4102 } else { // JavaScript is disabled, so DOM storage is ghosted.
4104 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4106 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4110 // Update the refresh icon.
4112 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
4114 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
4117 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4118 if (runInvalidateOptionsMenu) {
4119 invalidateOptionsMenu();
4123 private void highlightUrlText() {
4124 String urlString = urlTextBox.getText().toString();
4126 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4127 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4128 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4129 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4132 // Get the index of the `/` immediately after the domain name.
4133 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4135 // De-emphasize the text after the domain name.
4136 if (endOfDomainName > 0) {
4137 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4141 private void loadBookmarksFolder() {
4142 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
4143 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4145 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4146 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4148 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4149 // Inflate the individual item layout. `false` does not attach it to the root.
4150 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4154 public void bindView(View view, Context context, Cursor cursor) {
4155 // Get handles for the views.
4156 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4157 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4159 // Get the favorite icon byte array from the cursor.
4160 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4162 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4163 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4165 // Display the bitmap in `bookmarkFavoriteIcon`.
4166 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4168 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4169 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4170 bookmarkNameTextView.setText(bookmarkNameString);
4172 // Make the font bold for folders.
4173 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4174 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4175 } else { // Reset the font to default for normal bookmarks.
4176 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4181 // Populate the `ListView` with the adapter.
4182 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4184 // Set the bookmarks drawer title.
4185 if (currentBookmarksFolder.isEmpty()) {
4186 bookmarksTitleTextView.setText(R.string.bookmarks);
4188 bookmarksTitleTextView.setText(currentBookmarksFolder);