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()`.
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 fanboyAnnoyanceVersion;
198 public static String fanboySocialVersion;
200 // The request items are public static so they can be accessed by `BlockListHelper`, `RequestsArrayAdapter`, and `ViewRequestsDialog`. They are also used in `onCreate()`.
201 public static List<String[]> resourceRequests;
202 public static String[] whiteListResultStringArray;
203 public final static int REQUEST_DISPOSITION = 0;
204 public final static int REQUEST_URL = 1;
205 public final static int REQUEST_BLOCKLIST = 2;
206 public final static int REQUEST_SUBLIST = 3;
207 public final static int REQUEST_BLOCKLIST_ENTRIES = 4;
208 public final static int REQUEST_BLOCKLIST_ORIGINAL_ENTRY = 5;
210 public final static int REQUEST_DEFAULT = 0;
211 public final static int REQUEST_ALLOWED = 1;
212 public final static int REQUEST_BLOCKED = 2;
214 public final static int MAIN_WHITELIST = 1;
215 public final static int FINAL_WHITELIST = 2;
216 public final static int DOMAIN_WHITELIST = 3;
217 public final static int DOMAIN_INITIAL_WHITELIST = 4;
218 public final static int DOMAIN_FINAL_WHITELIST = 5;
219 public final static int THIRD_PARTY_WHITELIST = 6;
220 public final static int THIRD_PARTY_DOMAIN_WHITELIST = 7;
221 public final static int THIRD_PARTY_DOMAIN_INITIAL_WHITELIST = 8;
223 public final static int MAIN_BLACKLIST = 9;
224 public final static int INITIAL_BLACKLIST = 10;
225 public final static int FINAL_BLACKLIST = 11;
226 public final static int DOMAIN_BLACKLIST = 12;
227 public final static int DOMAIN_INITIAL_BLACKLIST = 13;
228 public final static int DOMAIN_FINAL_BLACKLIST = 14;
229 public final static int DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 15;
230 public final static int THIRD_PARTY_BLACKLIST = 16;
231 public final static int THIRD_PARTY_INITIAL_BLACKLIST = 17;
232 public final static int THIRD_PARTY_DOMAIN_BLACKLIST = 18;
233 public final static int THIRD_PARTY_DOMAIN_INITIAL_BLACKLIST = 19;
234 public final static int THIRD_PARTY_REGULAR_EXPRESSION_BLACKLIST = 20;
235 public final static int THIRD_PARTY_DOMAIN_REGULAR_EXPRESSION_BLACKLIST = 21;
236 public final static int REGULAR_EXPRESSION_BLACKLIST = 22;
238 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
239 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
240 public static String currentBookmarksFolder;
242 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
243 public static int domainSettingsDatabaseId;
245 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
246 public static String pinnedDomainSslIssuedToCNameString;
247 public static String pinnedDomainSslIssuedToONameString;
248 public static String pinnedDomainSslIssuedToUNameString;
249 public static String pinnedDomainSslIssuedByCNameString;
250 public static String pinnedDomainSslIssuedByONameString;
251 public static String pinnedDomainSslIssuedByUNameString;
252 public static Date pinnedDomainSslStartDate;
253 public static Date pinnedDomainSslEndDate;
255 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
256 public final static int UNRECOGNIZED_USER_AGENT = -1;
257 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
258 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
259 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
260 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
261 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
264 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
265 private ActionBar appBar;
267 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
268 private boolean navigatingHistory;
270 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
271 private Bitmap favoriteIconDefaultBitmap;
273 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
274 private DrawerLayout drawerLayout;
276 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
277 private CoordinatorLayout rootCoordinatorLayout;
279 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
280 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
281 private WebView mainWebView;
283 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
284 private FrameLayout fullScreenVideoFrameLayout;
286 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `onRestart()`.
287 private SwipeRefreshLayout swipeRefreshLayout;
289 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
290 private RelativeLayout urlAppBarRelativeLayout;
292 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
293 private ImageView favoriteIconImageView;
295 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
296 private CookieManager cookieManager;
298 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
299 private final Map<String, String> customHeaders = new HashMap<>();
301 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
302 private boolean javaScriptEnabled;
304 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
305 private boolean firstPartyCookiesEnabled;
307 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
308 private boolean thirdPartyCookiesEnabled;
310 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
311 private boolean domStorageEnabled;
313 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`. It can be removed once the minimum API >= 26.
314 private boolean saveFormDataEnabled;
316 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
317 private boolean nightMode;
319 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
320 private boolean displayWebpageImagesBoolean;
322 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
323 private String homepage;
325 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
326 private String searchURL;
328 // The block list variables are used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
329 private boolean easyListEnabled;
330 private boolean easyPrivacyEnabled;
331 private boolean fanboysAnnoyanceListEnabled;
332 private boolean fanboysSocialBlockingListEnabled;
334 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
335 private Runtime privacyBrowserRuntime;
337 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
338 private boolean proxyThroughOrbot;
340 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
341 private boolean incognitoModeEnabled;
343 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
344 private boolean fullScreenBrowsingModeEnabled;
346 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
347 private boolean inFullScreenBrowsingMode;
349 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
350 private boolean hideSystemBarsOnFullscreen;
352 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
353 private boolean translucentNavigationBarOnFullscreen;
355 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
356 private boolean reapplyDomainSettingsOnRestart;
358 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
359 private boolean reapplyAppSettingsOnRestart;
361 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
362 private String currentDomainName;
364 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
365 private boolean ignorePinnedSslCertificate;
367 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
368 private boolean waitingForOrbot;
370 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
371 private boolean domainSettingsApplied;
373 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
374 private int displayWebpageImagesInt;
376 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
377 private boolean onTheFlyDisplayImagesSet;
379 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
380 private String waitingForOrbotHTMLString;
382 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
383 private String privateDataDirectoryString;
385 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
386 private LinearLayout findOnPageLinearLayout;
388 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
389 private EditText findOnPageEditText;
391 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
392 private Menu mainMenu;
394 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
395 private ActionBarDrawerToggle drawerToggle;
397 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
398 private Toolbar supportAppBar;
400 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
401 private EditText urlTextBox;
403 // The color spans are used in `onCreate()` and `highlightUrlText()`.
404 private ForegroundColorSpan redColorSpan;
405 private ForegroundColorSpan initialGrayColorSpan;
406 private ForegroundColorSpan finalGrayColorSpan;
408 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
409 private SslErrorHandler sslErrorHandler;
411 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
412 private static HttpAuthHandler httpAuthHandler;
414 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
415 private InputMethodManager inputMethodManager;
417 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
418 private RelativeLayout mainWebViewRelativeLayout;
420 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
421 private boolean urlIsLoading;
423 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
424 private boolean pinnedDomainSslCertificate;
426 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
427 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
429 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
430 private ListView bookmarksListView;
432 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
433 private TextView bookmarksTitleTextView;
435 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
436 private Cursor bookmarksCursor;
438 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
439 private CursorAdapter bookmarksCursorAdapter;
441 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
442 private String oldFolderNameString;
444 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
445 private ValueCallback<Uri[]> fileChooserCallback;
447 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
448 private String downloadUrl;
449 private String downloadContentDisposition;
450 private long downloadContentLength;
452 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
453 private String downloadImageUrl;
455 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
456 private ArrayAdapter<CharSequence> userAgentNamesArray;
457 private String[] userAgentDataArray;
459 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
460 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
461 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
464 // 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.
465 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
466 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
467 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
468 @SuppressWarnings("deprecation")
469 protected void onCreate(Bundle savedInstanceState) {
470 // Get a handle for the shared preferences.
471 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
473 // Get the theme and screenshot preferences.
474 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
475 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
477 // Disable screenshots if not allowed.
478 if (!allowScreenshots) {
479 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
482 // Set the activity theme.
484 setTheme(R.style.PrivacyBrowserDark);
486 setTheme(R.style.PrivacyBrowserLight);
489 // Run the default commands.
490 super.onCreate(savedInstanceState);
492 // Set the content view.
493 setContentView(R.layout.main_drawerlayout);
495 // Get a handle for `inputMethodManager`.
496 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
498 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
499 supportAppBar = findViewById(R.id.app_bar);
500 setSupportActionBar(supportAppBar);
501 appBar = getSupportActionBar();
503 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
504 assert appBar != null;
506 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
507 appBar.setCustomView(R.layout.url_app_bar);
508 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
510 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
511 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
512 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
513 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
515 // Get a handle for `urlTextBox`.
516 urlTextBox = findViewById(R.id.url_edittext);
518 // Remove the formatting from `urlTextBar` when the user is editing the text.
519 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
520 if (hasFocus) { // The user is editing `urlTextBox`.
521 // Remove the highlighting.
522 urlTextBox.getText().removeSpan(redColorSpan);
523 urlTextBox.getText().removeSpan(initialGrayColorSpan);
524 urlTextBox.getText().removeSpan(finalGrayColorSpan);
525 } else { // The user has stopped editing `urlTextBox`.
526 // Reapply the highlighting.
531 // Set the go button on the keyboard to load the URL in `urlTextBox`.
532 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
533 // If the event is a key-down event on the `enter` button, load the URL.
534 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
535 // Load the URL into the mainWebView and consume the event.
537 loadUrlFromTextBox();
538 } catch (UnsupportedEncodingException e) {
541 // If the enter key was pressed, consume the event.
544 // If any other key was pressed, do not consume the event.
549 // Set `waitingForOrbotHTMLString`.
550 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
552 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
553 currentDomainName = "";
554 orbotStatus = "unknown";
555 waitingForOrbot = false;
557 // Create an Orbot status `BroadcastReceiver`.
558 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
560 public void onReceive(Context context, Intent intent) {
561 // Store the content of the status message in `orbotStatus`.
562 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
564 // If we are waiting on Orbot, load the website now that Orbot is connected.
565 if (orbotStatus.equals("ON") && waitingForOrbot) {
566 // Reset `waitingForOrbot`.
567 waitingForOrbot = false;
569 // Load `formattedUrlString
570 loadUrl(formattedUrlString);
575 // Register `orbotStatusBroadcastReceiver` on `this` context.
576 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
578 // Get handles for views that need to be accessed.
579 drawerLayout = findViewById(R.id.drawerlayout);
580 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
581 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
582 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
583 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
584 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
585 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
586 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
587 mainWebView = findViewById(R.id.main_webview);
588 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
589 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
590 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
591 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
592 favoriteIconImageView = findViewById(R.id.favorite_icon);
594 // 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.
596 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
597 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
598 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
599 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
601 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
602 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
603 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
604 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
607 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
608 launchBookmarksActivityFab.setOnClickListener(v -> {
609 // Create an intent to launch the bookmarks activity.
610 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
612 // Include the current folder with the `Intent`.
613 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
616 startActivity(bookmarksIntent);
619 // Set the create new bookmark folder FAB to display an alert dialog.
620 createBookmarkFolderFab.setOnClickListener(v -> {
621 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
622 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
623 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
626 // Set the create new bookmark FAB to display an alert dialog.
627 createBookmarkFab.setOnClickListener(view -> {
628 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
629 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
630 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
633 // Create a double-tap listener to toggle full-screen mode.
634 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
635 // Override `onDoubleTap()`. All other events are handled using the default settings.
637 public boolean onDoubleTap(MotionEvent event) {
638 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
639 // Toggle `inFullScreenBrowsingMode`.
640 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
642 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
643 // Hide the `appBar`.
646 // Hide the banner ad in the free flavor.
647 if (BuildConfig.FLAVOR.contentEquals("free")) {
648 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
649 AdHelper.hideAd(findViewById(R.id.adview));
652 // Modify the system bars.
653 if (hideSystemBarsOnFullscreen) { // Hide everything.
654 // Remove the translucent overlays.
655 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
657 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
658 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
660 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
661 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
662 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
664 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
666 // Set `rootCoordinatorLayout` to fill the whole screen.
667 rootCoordinatorLayout.setFitsSystemWindows(false);
668 } else { // Hide everything except the status and navigation bars.
669 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
670 rootCoordinatorLayout.setFitsSystemWindows(false);
672 // 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.
673 if (translucentNavigationBarOnFullscreen) {
674 // Set the navigation bar to be translucent.
675 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
678 } else { // Switch to normal viewing mode.
679 // Show the `appBar`.
682 // Show the `BannerAd` in the free flavor.
683 if (BuildConfig.FLAVOR.contentEquals("free")) {
684 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
685 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
688 // Remove the translucent navigation bar flag if it is set.
689 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
691 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
692 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
694 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
695 rootCoordinatorLayout.setSystemUiVisibility(0);
697 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
698 rootCoordinatorLayout.setFitsSystemWindows(true);
701 // Consume the double-tap.
703 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
709 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
710 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
711 // Call `performClick()` on the view, which is required for accessibility.
714 // Send the `event` to `gestureDetector`.
715 return gestureDetector.onTouchEvent(event);
718 // Update `findOnPageCountTextView`.
719 mainWebView.setFindListener(new WebView.FindListener() {
720 // Get a handle for `findOnPageCountTextView`.
721 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
724 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
725 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
726 // Set `findOnPageCountTextView` to `0/0`.
727 findOnPageCountTextView.setText(R.string.zero_of_zero);
728 } else if (isDoneCounting) { // There are matches.
729 // `activeMatchOrdinal` is zero-based.
730 int activeMatch = activeMatchOrdinal + 1;
732 // Build the match string.
733 String matchString = activeMatch + "/" + numberOfMatches;
735 // Set `findOnPageCountTextView`.
736 findOnPageCountTextView.setText(matchString);
741 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
742 findOnPageEditText.addTextChangedListener(new TextWatcher() {
744 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
749 public void onTextChanged(CharSequence s, int start, int before, int count) {
754 public void afterTextChanged(Editable s) {
755 // Search for the text in `mainWebView`.
756 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
760 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
761 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
762 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
763 // Hide the soft keyboard. `0` indicates no additional flags.
764 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
766 // Consume the event.
768 } else { // A different key was pressed.
769 // Do not consume the event.
774 // Implement swipe to refresh
775 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
776 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
777 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
779 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
780 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
781 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
783 // Listen for touches on the navigation menu.
784 final NavigationView navigationView = findViewById(R.id.navigationview);
785 navigationView.setNavigationItemSelectedListener(this);
787 // 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.
788 final Menu navigationMenu = navigationView.getMenu();
789 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
790 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
791 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
792 final MenuItem navigationRequestsMenuItem = navigationMenu.getItem(4);
794 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
795 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
796 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
798 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
799 currentBookmarksFolder = "";
801 // Load the home folder, which is `""` in the database.
802 loadBookmarksFolder();
804 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
805 // Convert the id from long to int to match the format of the bookmarks database.
806 int databaseID = (int) id;
808 // Get the bookmark cursor for this ID and move it to the first row.
809 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
810 bookmarkCursor.moveToFirst();
812 // Act upon the bookmark according to the type.
813 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
814 // Store the new folder name in `currentBookmarksFolder`.
815 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
817 // Load the new folder.
818 loadBookmarksFolder();
819 } else { // The selected bookmark is not a folder.
820 // Load the bookmark URL.
821 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
823 // Close the bookmarks drawer.
824 drawerLayout.closeDrawer(GravityCompat.END);
827 // Close the `Cursor`.
828 bookmarkCursor.close();
831 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
832 // Convert the database ID from `long` to `int`.
833 int databaseId = (int) id;
835 // Find out if the selected bookmark is a folder.
836 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
839 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
840 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
842 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
843 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
844 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
846 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
847 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
848 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
851 // Consume the event.
855 // The `DrawerListener` is used to update the Navigation Menu.
856 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
858 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
862 public void onDrawerOpened(@NonNull View drawerView) {
866 public void onDrawerClosed(@NonNull View drawerView) {
870 public void onDrawerStateChanged(int newState) {
871 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
872 // Initialize a the blocked requests counter.
873 int blockedRequests = 0;
875 // Count the number of blocked requests.
876 for (int i = 0; i < resourceRequests.size(); i++) {
877 if (Integer.valueOf(resourceRequests.get(i)[REQUEST_DISPOSITION]) == REQUEST_BLOCKED) {
882 // Update the back, forward, history, and requests menu items.
883 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
884 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
885 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
886 navigationRequestsMenuItem.setTitle(getResources().getString(R.string.requests) + " - " + blockedRequests);
888 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
889 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
891 // Clear the focus from `urlTextBox` if it has it.
892 urlTextBox.clearFocus();
897 // drawerToggle creates the hamburger icon at the start of the AppBar.
898 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
900 // Get a handle for the progress bar.
901 final ProgressBar progressBar = findViewById(R.id.progress_bar);
903 mainWebView.setWebChromeClient(new WebChromeClient() {
904 // Update the progress bar when a page is loading.
906 public void onProgressChanged(WebView view, int progress) {
907 // Inject the night mode CSS if night mode is enabled.
909 // `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
910 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
911 // `border: none` removes all borders, which can also be used to underline text.
912 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
913 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
914 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
915 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
916 // Initialize a `Handler` to display `mainWebView`.
917 Handler displayWebViewHandler = new Handler();
919 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
920 Runnable displayWebViewRunnable = () -> {
921 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
922 if (progressBar.getVisibility() == View.GONE) {
923 mainWebView.setVisibility(View.VISIBLE);
927 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
928 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
932 // Update the progress bar.
933 progressBar.setProgress(progress);
935 // Set the visibility of the progress bar.
936 if (progress < 100) {
937 // Show the progress bar.
938 progressBar.setVisibility(View.VISIBLE);
940 // Hide the progress bar.
941 progressBar.setVisibility(View.GONE);
943 // Display `mainWebView` if night mode is disabled.
944 // 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
945 // currently enabled.
947 mainWebView.setVisibility(View.VISIBLE);
950 //Stop the swipe to refresh indicator if it is running
951 swipeRefreshLayout.setRefreshing(false);
955 // Set the favorite icon when it changes.
957 public void onReceivedIcon(WebView view, Bitmap icon) {
958 // Only update the favorite icon if the website has finished loading.
959 if (progressBar.getVisibility() == View.GONE) {
960 // Save a copy of the favorite icon.
961 favoriteIconBitmap = icon;
963 // Place the favorite icon in the appBar.
964 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
968 // Save a copy of the title when it changes.
970 public void onReceivedTitle(WebView view, String title) {
971 // Save a copy of the title.
972 webViewTitle = title;
975 // Enter full screen video.
977 public void onShowCustomView(View view, CustomViewCallback callback) {
978 // Pause the ad if this is the free flavor.
979 if (BuildConfig.FLAVOR.contentEquals("free")) {
980 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
981 AdHelper.pauseAd(findViewById(R.id.adview));
984 // Remove the translucent overlays.
985 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
987 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
988 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
990 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
991 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
992 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
994 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
996 // Set `rootCoordinatorLayout` to fill the entire screen.
997 rootCoordinatorLayout.setFitsSystemWindows(false);
999 // Disable the sliding drawers.
1000 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
1002 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1003 fullScreenVideoFrameLayout.addView(view);
1004 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1007 // Exit full screen video.
1009 public void onHideCustomView() {
1010 // Hide `fullScreenVideoFrameLayout`.
1011 fullScreenVideoFrameLayout.removeAllViews();
1012 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1014 // Enable the sliding drawers.
1015 drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
1017 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1018 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1020 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1021 rootCoordinatorLayout.setFitsSystemWindows(true);
1023 // Show the ad if this is the free flavor.
1024 if (BuildConfig.FLAVOR.contentEquals("free")) {
1025 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1026 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
1032 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
1033 // Show the file chooser if the device is running API >= 21.
1034 if (Build.VERSION.SDK_INT >= 21) {
1035 // Store the file path callback.
1036 fileChooserCallback = filePathCallback;
1038 // Create an intent to open a chooser based ont the file chooser parameters.
1039 Intent fileChooserIntent = fileChooserParams.createIntent();
1041 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
1042 startActivityForResult(fileChooserIntent, 0);
1048 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1049 registerForContextMenu(mainWebView);
1051 // Allow the downloading of files.
1052 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1053 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1054 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1055 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1057 // Store the variables for future use by `onRequestPermissionsResult()`.
1059 downloadContentDisposition = contentDisposition;
1060 downloadContentLength = contentLength;
1062 // Show a dialog if the user has previously denied the permission.
1063 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1064 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1065 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1067 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1068 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1069 } else { // Show the permission request directly.
1070 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1071 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1073 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1074 // Get a handle for the download file alert dialog.
1075 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1077 // Show the download file alert dialog.
1078 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1082 // Allow pinch to zoom.
1083 mainWebView.getSettings().setBuiltInZoomControls(true);
1085 // Hide zoom controls.
1086 mainWebView.getSettings().setDisplayZoomControls(false);
1088 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1089 mainWebView.getSettings().setUseWideViewPort(true);
1091 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1092 mainWebView.getSettings().setLoadWithOverviewMode(true);
1094 // Explicitly disable geolocation.
1095 mainWebView.getSettings().setGeolocationEnabled(false);
1097 // Initialize cookieManager.
1098 cookieManager = CookieManager.getInstance();
1100 // 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).
1101 customHeaders.put("X-Requested-With", "");
1103 // Initialize the default preference values the first time the program is run. `this` is the context. `false` keeps this command from resetting any current preferences back to default.
1104 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1106 // Get the intent that started the app.
1107 final Intent launchingIntent = getIntent();
1109 // Extract the launching intent data as `launchingIntentUriData`.
1110 final Uri launchingIntentUriData = launchingIntent.getData();
1112 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1113 if (launchingIntentUriData != null) {
1114 formattedUrlString = launchingIntentUriData.toString();
1117 // Get a handle for the `Runtime`.
1118 privacyBrowserRuntime = Runtime.getRuntime();
1120 // Store the application's private data directory.
1121 privateDataDirectoryString = getApplicationInfo().dataDir;
1122 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1124 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1125 inFullScreenBrowsingMode = false;
1127 // Initialize the privacy settings variables.
1128 javaScriptEnabled = false;
1129 firstPartyCookiesEnabled = false;
1130 thirdPartyCookiesEnabled = false;
1131 domStorageEnabled = false;
1132 saveFormDataEnabled = false; // Form data can be removed once the minimum API >= 26.
1135 // Initialize the WebView title.
1136 webViewTitle = getString(R.string.no_title);
1138 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1139 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1140 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1141 assert favoriteIconBitmapDrawable != null;
1142 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1144 // If the favorite icon is null, load the default.
1145 if (favoriteIconBitmap == null) {
1146 favoriteIconBitmap = favoriteIconDefaultBitmap;
1149 // Initialize the user agent array adapter and string array.
1150 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1151 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1153 // Apply the app settings from the shared preferences.
1156 // Instantiate the block list helper.
1157 BlockListHelper blockListHelper = new BlockListHelper();
1159 // Initialize the list of resource requests.
1160 resourceRequests = new ArrayList<>();
1162 // Parse the block lists.
1163 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1164 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1165 final ArrayList<List<String[]>> fanboyAnnoyance = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1166 final ArrayList<List<String[]>> fanboySocial = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1168 // Store the list versions.
1169 easyListVersion = easyList.get(0).get(0)[0];
1170 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1171 fanboyAnnoyanceVersion = fanboyAnnoyance.get(0).get(0)[0];
1172 fanboySocialVersion = fanboySocial.get(0).get(0)[0];
1174 mainWebView.setWebViewClient(new WebViewClient() {
1175 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1176 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1177 @SuppressWarnings("deprecation")
1179 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1180 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1181 // Apply the domain settings for the new URL. `applyDomainSettings` doesn't do anything if the domain has not changed.
1182 applyDomainSettings(url, true, false);
1184 // Returning false causes the current WebView to handle the URL and prevents it from adding redirects to the history list.
1186 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1187 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1188 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1190 // Parse the url and set it as the data for the intent.
1191 emailIntent.setData(Uri.parse(url));
1193 // Open the email program in a new task instead of as part of Privacy Browser.
1194 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1197 startActivity(emailIntent);
1199 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1201 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1202 // Open the dialer and load the phone number, but wait for the user to place the call.
1203 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1205 // Add the phone number to the intent.
1206 dialIntent.setData(Uri.parse(url));
1208 // Open the dialer in a new task instead of as part of Privacy Browser.
1209 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1212 startActivity(dialIntent);
1214 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1216 } else { // Load a system chooser to select an app that can handle the URL.
1217 // Open an app that can handle the URL.
1218 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1220 // Add the URL to the intent.
1221 genericIntent.setData(Uri.parse(url));
1223 // List all apps that can handle the URL instead of just opening the first one.
1224 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1226 // Open the app in a new task instead of as part of Privacy Browser.
1227 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1229 // Start the app or display a snackbar if no app is available to handle the URL.
1231 startActivity(genericIntent);
1232 } catch (ActivityNotFoundException exception) {
1233 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1236 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1241 // Check requests against the block lists. The deprecated `shouldInterceptRequest()` must be used until minimum API >= 21.
1242 @SuppressWarnings("deprecation")
1244 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1245 // Create an empty web resource response to be used if the resource request is blocked.
1246 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1248 // Reset `whiteListResultStringArray`.
1249 whiteListResultStringArray = null;
1251 // Check EasyList if it is enabled.
1252 if (easyListEnabled) {
1253 if (blockListHelper.isBlocked(formattedUrlString, url, easyList)) {
1254 // The resource request was blocked. Return an empty web resource response.
1255 return emptyWebResourceResponse;
1259 // Check EasyPrivacy if it is enabled.
1260 if (easyPrivacyEnabled) {
1261 if (blockListHelper.isBlocked(formattedUrlString, url, easyPrivacy)) {
1262 // The resource request was blocked. Return an empty web resource response.
1263 return emptyWebResourceResponse;
1267 // Check Fanboy’s Annoyance List if it is enabled.
1268 if (fanboysAnnoyanceListEnabled) {
1269 if (blockListHelper.isBlocked(formattedUrlString, url, fanboyAnnoyance)) {
1270 // The resource request was blocked. Return an empty web resource response.
1271 return emptyWebResourceResponse;
1273 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1274 if (blockListHelper.isBlocked(formattedUrlString, url, fanboySocial)) {
1275 // The resource request was blocked. Return an empty web resource response.
1276 return emptyWebResourceResponse;
1280 // Add the request to the log.
1281 if (whiteListResultStringArray != null ) { // The request was processed by a whitelist.
1282 resourceRequests.add(whiteListResultStringArray);
1283 } else { // The request didn't match any blocklist entry. Log it as a defult request.
1284 resourceRequests.add(new String[]{String.valueOf(REQUEST_DEFAULT), url});
1287 // The resource request has not been blocked. `return null` loads the requested resource.
1291 // Handle HTTP authentication requests.
1293 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1294 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1295 httpAuthHandler = handler;
1297 // Display the HTTP authentication dialog.
1298 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1299 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1302 // Update the URL in urlTextBox when the page starts to load.
1304 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1305 // Reset the list of resource requests.
1306 resourceRequests.clear();
1308 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1310 mainWebView.setVisibility(View.INVISIBLE);
1313 // Hide the keyboard. `0` indicates no additional flags.
1314 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1316 // Check to see if Privacy Browser is waiting on Orbot.
1317 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1318 // 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.
1319 formattedUrlString = url;
1321 // Display the formatted URL text.
1322 urlTextBox.setText(formattedUrlString);
1324 // Apply text highlighting to `urlTextBox`.
1327 // Apply any custom domain settings if the URL was loaded by navigating history.
1328 if (navigatingHistory) {
1329 applyDomainSettings(url, true, false);
1332 // 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.
1333 urlIsLoading = true;
1337 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1339 public void onPageFinished(WebView view, String url) {
1340 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1341 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1342 cookieManager.flush();
1345 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1346 urlIsLoading = false;
1348 // Clear the cache and history if Incognito Mode is enabled.
1349 if (incognitoModeEnabled) {
1350 // Clear the cache. `true` includes disk files.
1351 mainWebView.clearCache(true);
1353 // Clear the back/forward history.
1354 mainWebView.clearHistory();
1356 // Manually delete cache folders.
1358 // Delete the main cache directory.
1359 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1361 // Delete the secondary `Service Worker` cache directory.
1362 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1363 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1364 } catch (IOException e) {
1365 // Do nothing if an error is thrown.
1369 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1370 if (!waitingForOrbot) {
1371 // Check to see if `WebView` has set `url` to be `about:blank`.
1372 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1373 // Set `formattedUrlString` to `""`.
1374 formattedUrlString = "";
1376 urlTextBox.setText(formattedUrlString);
1378 // Request focus for `urlTextBox`.
1379 urlTextBox.requestFocus();
1381 // Display the keyboard.
1382 inputMethodManager.showSoftInput(urlTextBox, 0);
1384 // Apply the domain settings. This clears any settings from the previous domain.
1385 applyDomainSettings(formattedUrlString, true, false);
1386 } else { // `WebView` has loaded a webpage.
1387 // Set `formattedUrlString`.
1388 formattedUrlString = url;
1390 // Only update `urlTextBox` if the user is not typing in it.
1391 if (!urlTextBox.hasFocus()) {
1392 // Display the formatted URL text.
1393 urlTextBox.setText(formattedUrlString);
1395 // Apply text highlighting to `urlTextBox`.
1400 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1401 sslCertificate = mainWebView.getCertificate();
1403 // 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.
1404 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1405 // Initialize the current SSL certificate variables.
1406 String currentWebsiteIssuedToCName = "";
1407 String currentWebsiteIssuedToOName = "";
1408 String currentWebsiteIssuedToUName = "";
1409 String currentWebsiteIssuedByCName = "";
1410 String currentWebsiteIssuedByOName = "";
1411 String currentWebsiteIssuedByUName = "";
1412 Date currentWebsiteSslStartDate = null;
1413 Date currentWebsiteSslEndDate = null;
1416 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1417 if (sslCertificate != null) {
1418 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1419 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1420 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1421 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1422 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1423 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1424 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1425 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1428 // 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`.
1429 String currentWebsiteSslStartDateString = "";
1430 String currentWebsiteSslEndDateString = "";
1431 String pinnedDomainSslStartDateString = "";
1432 String pinnedDomainSslEndDateString = "";
1434 // Convert the `Dates` to `Strings` if they are not `null`.
1435 if (currentWebsiteSslStartDate != null) {
1436 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1439 if (currentWebsiteSslEndDate != null) {
1440 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1443 if (pinnedDomainSslStartDate != null) {
1444 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1447 if (pinnedDomainSslEndDate != null) {
1448 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1451 // Check to see if the pinned SSL certificate matches the current website certificate.
1452 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1453 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1454 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1455 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1456 // The pinned SSL certificate doesn't match the current domain certificate.
1457 //Display the pinned SSL certificate mismatch `AlertDialog`.
1458 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1459 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1465 // Handle SSL Certificate errors.
1467 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1468 // Get the current website SSL certificate.
1469 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1471 // Extract the individual pieces of information from the current website SSL certificate.
1472 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1473 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1474 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1475 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1476 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1477 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1478 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1479 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1481 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1482 if (pinnedDomainSslCertificate &&
1483 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1484 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1485 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1486 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1487 // An SSL certificate is pinned and matches the current domain certificate.
1488 // Proceed to the website without displaying an error.
1490 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1491 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1492 sslErrorHandler = handler;
1494 // Display the SSL error `AlertDialog`.
1495 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1496 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1501 // Load the website if not waiting for Orbot to connect.
1502 if (!waitingForOrbot) {
1503 loadUrl(formattedUrlString);
1508 protected void onNewIntent(Intent intent) {
1509 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1512 // Check to see if the intent contains a new URL.
1513 if (intent.getData() != null) {
1514 // Get the intent data and convert it to a string.
1515 final Uri intentUriData = intent.getData();
1516 formattedUrlString = intentUriData.toString();
1518 // Load the website.
1519 loadUrl(formattedUrlString);
1521 // Close the navigation drawer if it is open.
1522 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1523 drawerLayout.closeDrawer(GravityCompat.START);
1526 // Close the bookmarks drawer if it is open.
1527 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1528 drawerLayout.closeDrawer(GravityCompat.END);
1531 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1532 mainWebView.requestFocus();
1537 public void onRestart() {
1538 // Run the default commands.
1541 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1542 if (proxyThroughOrbot) {
1543 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1544 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1546 // Send the intent to the Orbot package.
1547 orbotIntent.setPackage("org.torproject.android");
1550 sendBroadcast(orbotIntent);
1553 // Apply the app settings if returning from the Settings activity..
1554 if (reapplyAppSettingsOnRestart) {
1555 // Apply the app settings.
1558 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1559 if (reloadOnRestart) {
1560 // Reload `mainWebView`.
1561 mainWebView.reload();
1563 // Reset `reloadOnRestartBoolean`.
1564 reloadOnRestart = false;
1567 // Reset the return from settings flag.
1568 reapplyAppSettingsOnRestart = false;
1571 // Apply the domain settings if returning from the Domains activity.
1572 if (reapplyDomainSettingsOnRestart) {
1573 // Reapply the domain settings.
1574 applyDomainSettings(formattedUrlString, false, true);
1576 // Reset `reapplyDomainSettingsOnRestart`.
1577 reapplyDomainSettingsOnRestart = false;
1580 // Load the URL on restart to apply changes to night mode.
1581 if (loadUrlOnRestart) {
1582 // Load the current `formattedUrlString`.
1583 loadUrl(formattedUrlString);
1585 // Reset `loadUrlOnRestart.
1586 loadUrlOnRestart = false;
1589 // Update the bookmarks drawer if returning from the Bookmarks activity.
1590 if (restartFromBookmarksActivity) {
1591 // Close the bookmarks drawer.
1592 drawerLayout.closeDrawer(GravityCompat.END);
1594 // Reload the bookmarks drawer.
1595 loadBookmarksFolder();
1597 // Reset `restartFromBookmarksActivity`.
1598 restartFromBookmarksActivity = false;
1601 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1602 updatePrivacyIcons(true);
1605 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1607 public void onResume() {
1608 // Run the default commands.
1611 // Resume JavaScript (if enabled).
1612 mainWebView.resumeTimers();
1614 // Resume `mainWebView`.
1615 mainWebView.onResume();
1617 // Resume the adView for the free flavor.
1618 if (BuildConfig.FLAVOR.contentEquals("free")) {
1619 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1620 AdHelper.resumeAd(findViewById(R.id.adview));
1625 public void onPause() {
1626 // Pause `mainWebView`.
1627 mainWebView.onPause();
1629 // Stop all JavaScript.
1630 mainWebView.pauseTimers();
1632 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1633 if (BuildConfig.FLAVOR.contentEquals("free")) {
1634 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1635 AdHelper.pauseAd(findViewById(R.id.adview));
1642 public boolean onCreateOptionsMenu(Menu menu) {
1643 // Inflate the menu; this adds items to the action bar if it is present.
1644 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1646 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1649 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1650 updatePrivacyIcons(false);
1652 // Get handles for the menu items.
1653 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1654 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1655 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1656 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1657 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1658 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1659 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1661 // Only display third-party cookies if API >= 21
1662 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1664 // Only display the form data menu items if the API < 26.
1665 toggleSaveFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1666 clearFormDataMenuItem.setVisible(Build.VERSION.SDK_INT < 26);
1668 // Only show Ad Consent if this is the free flavor.
1669 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1671 // Get the shared preference values. `this` references the current context.
1672 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1674 // 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.
1675 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1676 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1677 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1678 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1679 } else { //Do not display the additional icons.
1680 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1681 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1682 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1689 public boolean onPrepareOptionsMenu(Menu menu) {
1690 // Get handles for the menu items.
1691 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1692 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1693 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1694 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1695 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data); // Form data can be removed once the minimum API >= 26.
1696 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1697 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1698 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1699 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data); // Form data can be removed once the minimum API >= 26.
1700 MenuItem easyListMenuItem = menu.findItem(R.id.easylist);
1701 MenuItem easyPrivacyMenuItem = menu.findItem(R.id.easyprivacy);
1702 MenuItem fanboysAnnoyanceListMenuItem = menu.findItem(R.id.fanboys_annoyance_list);
1703 MenuItem fanboysSocialBlockingListMenuItem = menu.findItem(R.id.fanboys_social_blocking_list);
1704 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1705 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1706 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1708 // Set the text for the domain menu item.
1709 if (domainSettingsApplied) {
1710 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1712 addOrEditDomain.setTitle(R.string.add_domain_settings);
1715 // Set the status of the menu item checkboxes.
1716 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1717 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1718 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1719 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled); // Form data can be removed once the minimum API >= 26.
1720 easyListMenuItem.setChecked(easyListEnabled);
1721 easyPrivacyMenuItem.setChecked(easyPrivacyEnabled);
1722 fanboysAnnoyanceListMenuItem.setChecked(fanboysAnnoyanceListEnabled);
1723 fanboysSocialBlockingListMenuItem.setChecked(fanboysSocialBlockingListEnabled);
1724 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1725 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1727 // Enable third-party cookies if first-party cookies are enabled.
1728 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1730 // Enable DOM Storage if JavaScript is enabled.
1731 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1733 // Enable Clear Cookies if there are any.
1734 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1736 // Get a count of the number of files in the Local Storage directory.
1737 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1738 int localStorageDirectoryNumberOfFiles = 0;
1739 if (localStorageDirectory.exists()) {
1740 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1743 // Get a count of the number of files in the IndexedDB directory.
1744 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1745 int indexedDBDirectoryNumberOfFiles = 0;
1746 if (indexedDBDirectory.exists()) {
1747 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1750 // Enable Clear DOM Storage if there is any.
1751 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1753 // Enable Clear Form Data is there is any. This can be removed once the minimum API >= 26.
1754 if (Build.VERSION.SDK_INT < 26) {
1755 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1756 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1759 // Enable Clear Data if any of the submenu items are enabled.
1760 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1762 // Disable Fanboy's Social Blocking List if Fanboy's Annoyance List is checked.
1763 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
1765 // Initialize font size variables.
1766 int fontSize = mainWebView.getSettings().getTextZoom();
1767 String fontSizeTitle;
1768 MenuItem selectedFontSizeMenuItem;
1770 // Prepare the font size title and current size menu item.
1773 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1774 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1778 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1779 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1783 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1784 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1788 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1789 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1793 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1794 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1798 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1799 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1803 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1804 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1808 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1809 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1813 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1814 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1818 // Set the font size title and select the current size menu item.
1819 fontSizeMenuItem.setTitle(fontSizeTitle);
1820 selectedFontSizeMenuItem.setChecked(true);
1822 // Run all the other default commands.
1823 super.onPrepareOptionsMenu(menu);
1825 // Display the menu.
1830 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1831 @SuppressLint("SetJavaScriptEnabled")
1832 // removeAllCookies is deprecated, but it is required for API < 21.
1833 @SuppressWarnings("deprecation")
1834 public boolean onOptionsItemSelected(MenuItem menuItem) {
1835 // Get the selected menu item ID.
1836 int menuItemId = menuItem.getItemId();
1838 // Set the commands that relate to the menu entries.
1839 switch (menuItemId) {
1840 case R.id.toggle_javascript:
1841 // Switch the status of javaScriptEnabled.
1842 javaScriptEnabled = !javaScriptEnabled;
1844 // Apply the new JavaScript status.
1845 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1847 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1848 updatePrivacyIcons(true);
1850 // Display a `Snackbar`.
1851 if (javaScriptEnabled) { // JavaScrip is enabled.
1852 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1853 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1854 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1855 } else { // Privacy mode.
1856 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1859 // Reload the WebView.
1860 mainWebView.reload();
1863 case R.id.add_or_edit_domain:
1864 if (domainSettingsApplied) { // Edit the current domain settings.
1865 // Reapply the domain settings on returning to `MainWebViewActivity`.
1866 reapplyDomainSettingsOnRestart = true;
1867 currentDomainName = "";
1869 // Create an intent to launch the domains activity.
1870 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1872 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
1873 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
1874 domainsIntent.putExtra("closeOnBack", true);
1877 startActivity(domainsIntent);
1878 } else { // Add a new domain.
1879 // Apply the new domain settings on returning to `MainWebViewActivity`.
1880 reapplyDomainSettingsOnRestart = true;
1881 currentDomainName = "";
1883 // Get the current domain
1884 Uri currentUri = Uri.parse(formattedUrlString);
1885 String currentDomain = currentUri.getHost();
1887 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1888 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1890 // Create the domain and store the database ID.
1891 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1893 // Create an intent to launch the domains activity.
1894 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1896 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
1897 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
1898 domainsIntent.putExtra("closeOnBack", true);
1901 startActivity(domainsIntent);
1905 case R.id.toggle_first_party_cookies:
1906 // Switch the status of firstPartyCookiesEnabled.
1907 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1909 // Update the menu checkbox.
1910 menuItem.setChecked(firstPartyCookiesEnabled);
1912 // Apply the new cookie status.
1913 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1915 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1916 updatePrivacyIcons(true);
1918 // Display a `Snackbar`.
1919 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1920 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1921 } else if (javaScriptEnabled) { // JavaScript is still enabled.
1922 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1923 } else { // Privacy mode.
1924 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1927 // Reload the WebView.
1928 mainWebView.reload();
1931 case R.id.toggle_third_party_cookies:
1932 if (Build.VERSION.SDK_INT >= 21) {
1933 // Switch the status of thirdPartyCookiesEnabled.
1934 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1936 // Update the menu checkbox.
1937 menuItem.setChecked(thirdPartyCookiesEnabled);
1939 // Apply the new cookie status.
1940 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1942 // Display a `Snackbar`.
1943 if (thirdPartyCookiesEnabled) {
1944 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1946 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1949 // Reload the WebView.
1950 mainWebView.reload();
1951 } // Else do nothing because SDK < 21.
1954 case R.id.toggle_dom_storage:
1955 // Switch the status of domStorageEnabled.
1956 domStorageEnabled = !domStorageEnabled;
1958 // Update the menu checkbox.
1959 menuItem.setChecked(domStorageEnabled);
1961 // Apply the new DOM Storage status.
1962 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1964 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1965 updatePrivacyIcons(true);
1967 // Display a `Snackbar`.
1968 if (domStorageEnabled) {
1969 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1971 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1974 // Reload the WebView.
1975 mainWebView.reload();
1978 // Form data can be removed once the minimum API >= 26.
1979 case R.id.toggle_save_form_data:
1980 // Switch the status of saveFormDataEnabled.
1981 saveFormDataEnabled = !saveFormDataEnabled;
1983 // Update the menu checkbox.
1984 menuItem.setChecked(saveFormDataEnabled);
1986 // Apply the new form data status.
1987 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1989 // Display a `Snackbar`.
1990 if (saveFormDataEnabled) {
1991 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1993 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1996 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1997 updatePrivacyIcons(true);
1999 // Reload the WebView.
2000 mainWebView.reload();
2003 case R.id.clear_cookies:
2004 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2005 .setAction(R.string.undo, v -> {
2006 // Do nothing because everything will be handled by `onDismissed()` below.
2008 .addCallback(new Snackbar.Callback() {
2010 public void onDismissed(Snackbar snackbar, int event) {
2012 // The user pushed the `Undo` button.
2013 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2017 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2019 // `cookieManager.removeAllCookie()` varies by SDK.
2020 if (Build.VERSION.SDK_INT < 21) {
2021 cookieManager.removeAllCookie();
2023 // `null` indicates no callback.
2024 cookieManager.removeAllCookies(null);
2032 case R.id.clear_dom_storage:
2033 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2034 .setAction(R.string.undo, v -> {
2035 // Do nothing because everything will be handled by `onDismissed()` below.
2037 .addCallback(new Snackbar.Callback() {
2039 public void onDismissed(Snackbar snackbar, int event) {
2041 // The user pushed the `Undo` button.
2042 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2046 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2048 // Delete the DOM Storage.
2049 WebStorage webStorage = WebStorage.getInstance();
2050 webStorage.deleteAllData();
2052 // Manually delete the DOM storage files and directories.
2054 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2055 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2057 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2058 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2059 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2060 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2061 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2062 } catch (IOException e) {
2063 // Do nothing if an error is thrown.
2071 // Form data can be remove once the minimum API >= 26.
2072 case R.id.clear_form_data:
2073 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2074 .setAction(R.string.undo, v -> {
2075 // Do nothing because everything will be handled by `onDismissed()` below.
2077 .addCallback(new Snackbar.Callback() {
2079 public void onDismissed(Snackbar snackbar, int event) {
2081 // The user pushed the `Undo` button.
2082 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2086 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2088 // Delete the form data.
2089 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2090 mainWebViewDatabase.clearFormData();
2097 case R.id.font_size_twenty_five_percent:
2098 mainWebView.getSettings().setTextZoom(25);
2101 case R.id.font_size_fifty_percent:
2102 mainWebView.getSettings().setTextZoom(50);
2105 case R.id.font_size_seventy_five_percent:
2106 mainWebView.getSettings().setTextZoom(75);
2109 case R.id.font_size_one_hundred_percent:
2110 mainWebView.getSettings().setTextZoom(100);
2113 case R.id.font_size_one_hundred_twenty_five_percent:
2114 mainWebView.getSettings().setTextZoom(125);
2117 case R.id.font_size_one_hundred_fifty_percent:
2118 mainWebView.getSettings().setTextZoom(150);
2121 case R.id.font_size_one_hundred_seventy_five_percent:
2122 mainWebView.getSettings().setTextZoom(175);
2125 case R.id.font_size_two_hundred_percent:
2126 mainWebView.getSettings().setTextZoom(200);
2129 case R.id.swipe_to_refresh:
2130 // Toggle swipe to refresh.
2131 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2134 case R.id.display_images:
2135 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2136 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2137 mainWebView.reload();
2138 } else { // Images are not currently loaded automatically.
2139 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2142 // Set `onTheFlyDisplayImagesSet`.
2143 onTheFlyDisplayImagesSet = true;
2146 case R.id.view_source:
2147 // Launch the View Source activity.
2148 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2149 startActivity(viewSourceIntent);
2153 // Toggle the EasyList status.
2154 easyListEnabled = !easyListEnabled;
2156 // Update the menu checkbox.
2157 menuItem.setChecked(easyListEnabled);
2159 // Reload the main WebView.
2160 mainWebView.reload();
2163 case R.id.easyprivacy:
2164 // Toggle the EasyPrivacy status.
2165 easyPrivacyEnabled = !easyPrivacyEnabled;
2167 // Update the menu checkbox.
2168 menuItem.setChecked(easyPrivacyEnabled);
2170 // Reload the main WebView.
2171 mainWebView.reload();
2174 case R.id.fanboys_annoyance_list:
2175 // Toggle Fanboy's Annoyance List status.
2176 fanboysAnnoyanceListEnabled = !fanboysAnnoyanceListEnabled;
2178 // Update the menu checkbox.
2179 menuItem.setChecked(fanboysAnnoyanceListEnabled);
2181 // Update the staus of Fanboy's Social Blocking List.
2182 MenuItem fanboysSocialBlockingListMenuItem = mainMenu.findItem(R.id.fanboys_social_blocking_list);
2183 fanboysSocialBlockingListMenuItem.setEnabled(!fanboysAnnoyanceListEnabled);
2185 // Reload the main WebView.
2186 mainWebView.reload();
2189 case R.id.fanboys_social_blocking_list:
2190 // Toggle Fanboy's Social Blocking List status.
2191 fanboysSocialBlockingListEnabled = !fanboysSocialBlockingListEnabled;
2193 // Update teh menu checkbox.
2194 menuItem.setChecked(fanboysSocialBlockingListEnabled);
2196 // Reload the main WebView.
2197 mainWebView.reload();
2201 // Setup the share string.
2202 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2204 // Create the share intent.
2205 Intent shareIntent = new Intent();
2206 shareIntent.setAction(Intent.ACTION_SEND);
2207 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2208 shareIntent.setType("text/plain");
2211 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2214 case R.id.find_on_page:
2215 // Hide the URL app bar.
2216 supportAppBar.setVisibility(View.GONE);
2218 // Show the Find on Page `RelativeLayout`.
2219 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2221 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2222 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2223 findOnPageEditText.postDelayed(() -> {
2224 // Set the focus on `findOnPageEditText`.
2225 findOnPageEditText.requestFocus();
2227 // Display the keyboard. `0` sets no input flags.
2228 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2233 // Get a `PrintManager` instance.
2234 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2236 // Convert `mainWebView` to `printDocumentAdapter`.
2237 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2239 // Remove the lint error below that `printManager` might be `null`.
2240 assert printManager != null;
2242 // Print the document. The print attributes are `null`.
2243 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2246 case R.id.add_to_homescreen:
2247 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2248 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2249 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2251 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2255 mainWebView.reload();
2258 case R.id.ad_consent:
2259 // Display the ad consent dialog.
2260 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2261 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2265 // Don't consume the event.
2266 return super.onOptionsItemSelected(menuItem);
2270 // removeAllCookies is deprecated, but it is required for API < 21.
2271 @SuppressWarnings("deprecation")
2273 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2274 int menuItemId = menuItem.getItemId();
2276 switch (menuItemId) {
2282 if (mainWebView.canGoBack()) {
2283 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2284 navigatingHistory = true;
2286 // Load the previous website in the history.
2287 mainWebView.goBack();
2292 if (mainWebView.canGoForward()) {
2293 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2294 navigatingHistory = true;
2296 // Load the next website in the history.
2297 mainWebView.goForward();
2302 // Get the `WebBackForwardList`.
2303 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2305 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2306 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2307 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2311 // Launch the requests activity.
2312 Intent requestsIntent = new Intent(this, RequestsActivity.class);
2313 startActivity(requestsIntent);
2316 case R.id.downloads:
2317 // Launch the system Download Manager.
2318 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2320 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2321 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2323 startActivity(downloadManagerIntent);
2327 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2328 reapplyDomainSettingsOnRestart = true;
2329 currentDomainName = "";
2331 // Launch the domains activity.
2332 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2333 startActivity(domainsIntent);
2337 // Set the flag to reapply app settings on restart when returning from Settings.
2338 reapplyAppSettingsOnRestart = true;
2340 // Set the flag to reapply the domain settings on restart when returning from Settings.
2341 reapplyDomainSettingsOnRestart = true;
2342 currentDomainName = "";
2344 // Launch the settings activity.
2345 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2346 startActivity(settingsIntent);
2350 // Launch `GuideActivity`.
2351 Intent guideIntent = new Intent(this, GuideActivity.class);
2352 startActivity(guideIntent);
2356 // Launch `AboutActivity`.
2357 Intent aboutIntent = new Intent(this, AboutActivity.class);
2358 startActivity(aboutIntent);
2361 case R.id.clearAndExit:
2362 // Get a handle for `sharedPreferences`. `this` references the current context.
2363 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2365 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2368 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2369 // The command to remove cookies changed slightly in API 21.
2370 if (Build.VERSION.SDK_INT >= 21) {
2371 cookieManager.removeAllCookies(null);
2373 cookieManager.removeAllCookie();
2376 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2378 // We have to use two commands because `Runtime.exec()` does not like `*`.
2379 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2380 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2381 } catch (IOException e) {
2382 // Do nothing if an error is thrown.
2386 // Clear DOM storage.
2387 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2388 // Ask `WebStorage` to clear the DOM storage.
2389 WebStorage webStorage = WebStorage.getInstance();
2390 webStorage.deleteAllData();
2392 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2394 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2395 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2397 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2398 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2399 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2400 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2401 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2402 } catch (IOException e) {
2403 // Do nothing if an error is thrown.
2407 // Clear form data if the API < 26.
2408 if ((Build.VERSION.SDK_INT < 26) && (clearEverything || sharedPreferences.getBoolean("clear_form_data", true))) {
2409 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2410 webViewDatabase.clearFormData();
2412 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2414 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2415 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2416 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2417 } catch (IOException e) {
2418 // Do nothing if an error is thrown.
2423 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2424 // `true` includes disk files.
2425 mainWebView.clearCache(true);
2427 // Manually delete the cache directories.
2429 // Delete the main cache directory.
2430 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2432 // Delete the secondary `Service Worker` cache directory.
2433 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2434 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2435 } catch (IOException e) {
2436 // Do nothing if an error is thrown.
2440 // Clear SSL certificate preferences.
2441 mainWebView.clearSslPreferences();
2443 // Clear the back/forward history.
2444 mainWebView.clearHistory();
2446 // Clear `formattedUrlString`.
2447 formattedUrlString = null;
2449 // Clear `customHeaders`.
2450 customHeaders.clear();
2452 // Detach all views from `mainWebViewRelativeLayout`.
2453 mainWebViewRelativeLayout.removeAllViews();
2455 // Destroy the internal state of `mainWebView`.
2456 mainWebView.destroy();
2458 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2459 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2460 if (clearEverything) {
2462 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2463 } catch (IOException e) {
2464 // Do nothing if an error is thrown.
2468 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2469 if (Build.VERSION.SDK_INT >= 21) {
2470 finishAndRemoveTask();
2475 // Remove the terminated program from RAM. The status code is `0`.
2480 // Close the navigation drawer.
2481 drawerLayout.closeDrawer(GravityCompat.START);
2486 public void onPostCreate(Bundle savedInstanceState) {
2487 super.onPostCreate(savedInstanceState);
2489 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2490 drawerToggle.syncState();
2494 public void onConfigurationChanged(Configuration newConfig) {
2495 super.onConfigurationChanged(newConfig);
2497 // Reload the ad for the free flavor if we are not in full screen mode.
2498 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2499 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2500 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2503 // `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:
2504 // https://code.google.com/p/android/issues/detail?id=20493#c8
2505 // ActivityCompat.invalidateOptionsMenu(this);
2509 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2510 // Store the `HitTestResult`.
2511 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2514 final String imageUrl;
2515 final String linkUrl;
2517 // Get a handle for the `ClipboardManager`.
2518 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2520 // Remove the lint errors below that `clipboardManager` might be `null`.
2521 assert clipboardManager != null;
2523 switch (hitTestResult.getType()) {
2524 // `SRC_ANCHOR_TYPE` is a link.
2525 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2526 // Get the target URL.
2527 linkUrl = hitTestResult.getExtra();
2529 // Set the target URL as the title of the `ContextMenu`.
2530 menu.setHeaderTitle(linkUrl);
2532 // Add a Load URL entry.
2533 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2538 // Add a Copy URL entry.
2539 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2540 // Save the link URL in a `ClipData`.
2541 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2543 // Set the `ClipData` as the clipboard's primary clip.
2544 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2548 // Add a Download URL entry.
2549 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2550 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2551 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2552 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2554 // Store the variables for future use by `onRequestPermissionsResult()`.
2555 downloadUrl = linkUrl;
2556 downloadContentDisposition = "none";
2557 downloadContentLength = -1;
2559 // Show a dialog if the user has previously denied the permission.
2560 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2561 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2562 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2564 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2565 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2566 } else { // Show the permission request directly.
2567 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2568 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2570 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2571 // Get a handle for the download file alert dialog.
2572 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2574 // Show the download file alert dialog.
2575 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2580 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2581 menu.add(R.string.cancel);
2584 case WebView.HitTestResult.EMAIL_TYPE:
2585 // Get the target URL.
2586 linkUrl = hitTestResult.getExtra();
2588 // Set the target URL as the title of the `ContextMenu`.
2589 menu.setHeaderTitle(linkUrl);
2591 // Add a `Write Email` entry.
2592 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2593 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2594 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2596 // Parse the url and set it as the data for the `Intent`.
2597 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2599 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2600 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2603 startActivity(emailIntent);
2607 // Add a `Copy Email Address` entry.
2608 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2609 // Save the email address in a `ClipData`.
2610 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2612 // Set the `ClipData` as the clipboard's primary clip.
2613 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2617 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2618 menu.add(R.string.cancel);
2621 // `IMAGE_TYPE` is an image.
2622 case WebView.HitTestResult.IMAGE_TYPE:
2623 // Get the image URL.
2624 imageUrl = hitTestResult.getExtra();
2626 // Set the image URL as the title of the `ContextMenu`.
2627 menu.setHeaderTitle(imageUrl);
2629 // Add a `View Image` entry.
2630 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2635 // Add a `Download Image` entry.
2636 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2637 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2638 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2639 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2641 // Store the image URL for use by `onRequestPermissionResult()`.
2642 downloadImageUrl = imageUrl;
2644 // Show a dialog if the user has previously denied the permission.
2645 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2646 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2647 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2649 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2650 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2651 } else { // Show the permission request directly.
2652 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2653 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2655 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2656 // Get a handle for the download image alert dialog.
2657 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2659 // Show the download image alert dialog.
2660 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2665 // Add a `Copy URL` entry.
2666 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2667 // Save the image URL in a `ClipData`.
2668 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2670 // Set the `ClipData` as the clipboard's primary clip.
2671 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2675 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2676 menu.add(R.string.cancel);
2680 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2681 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2682 // Get the image URL.
2683 imageUrl = hitTestResult.getExtra();
2685 // Set the image URL as the title of the `ContextMenu`.
2686 menu.setHeaderTitle(imageUrl);
2688 // Add a `View Image` entry.
2689 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2694 // Add a `Download Image` entry.
2695 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2696 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2697 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2698 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2700 // Store the image URL for use by `onRequestPermissionResult()`.
2701 downloadImageUrl = imageUrl;
2703 // Show a dialog if the user has previously denied the permission.
2704 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2705 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2706 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2708 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2709 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2710 } else { // Show the permission request directly.
2711 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2712 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2714 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2715 // Get a handle for the download image alert dialog.
2716 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2718 // Show the download image alert dialog.
2719 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2724 // Add a `Copy URL` entry.
2725 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2726 // Save the image URL in a `ClipData`.
2727 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2729 // Set the `ClipData` as the clipboard's primary clip.
2730 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2734 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2735 menu.add(R.string.cancel);
2741 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2742 // Get the `EditTexts` from the `dialogFragment`.
2743 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2744 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2746 // Extract the strings from the `EditTexts`.
2747 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2748 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2750 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2751 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2752 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2753 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2755 // Display the new bookmark below the current items in the (0 indexed) list.
2756 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2758 // Create the bookmark.
2759 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2761 // Update `bookmarksCursor` with the current contents of this folder.
2762 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2764 // Update the `ListView`.
2765 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2767 // Scroll to the new bookmark.
2768 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2772 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2773 // Get handles for the views in `dialogFragment`.
2774 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2775 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2776 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2778 // Get new folder name string.
2779 String folderNameString = createFolderNameEditText.getText().toString();
2781 // Get the new folder icon `Bitmap`.
2782 Bitmap folderIconBitmap;
2783 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2784 // Get the default folder icon and convert it to a `Bitmap`.
2785 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2786 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2787 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2788 } else { // Use the `WebView` favorite icon.
2789 folderIconBitmap = favoriteIconBitmap;
2792 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2793 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2794 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2795 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2797 // Move all the bookmarks down one in the display order.
2798 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2799 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2800 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2803 // Create the folder, which will be placed at the top of the `ListView`.
2804 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2806 // Update `bookmarksCursor` with the current contents of this folder.
2807 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2809 // Update the `ListView`.
2810 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2812 // Scroll to the new folder.
2813 bookmarksListView.setSelection(0);
2817 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2818 // Get the shortcut name.
2819 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2820 String shortcutNameString = shortcutNameEditText.getText().toString();
2822 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2823 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2825 // Setup the shortcut intent.
2826 Intent shortcutIntent = new Intent();
2827 shortcutIntent.setAction(Intent.ACTION_VIEW);
2828 shortcutIntent.setData(Uri.parse(formattedUrlString));
2830 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2831 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2833 // Add the required fields to the shortcut info builder.
2834 shortcutInfoBuilder.setIcon(favoriteIcon);
2835 shortcutInfoBuilder.setIntent(shortcutIntent);
2836 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2838 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2839 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2843 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2844 switch (downloadType) {
2845 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2846 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2847 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2850 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2851 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2852 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2858 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
2859 switch (requestCode) {
2860 case DOWNLOAD_FILE_REQUEST_CODE:
2861 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2862 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2864 // On API 23, displaying the fragment must be delayed or the app will crash.
2865 if (Build.VERSION.SDK_INT == 23) {
2866 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2868 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2871 // Reset the download variables.
2873 downloadContentDisposition = "";
2874 downloadContentLength = 0;
2877 case DOWNLOAD_IMAGE_REQUEST_CODE:
2878 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2879 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2881 // On API 23, displaying the fragment must be delayed or the app will crash.
2882 if (Build.VERSION.SDK_INT == 23) {
2883 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2885 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2888 // Reset the image URL variable.
2889 downloadImageUrl = "";
2895 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2896 // Download the image if it has an HTTP or HTTPS URI.
2897 if (imageUrl.startsWith("http")) {
2898 // Get a handle for the system `DOWNLOAD_SERVICE`.
2899 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2901 // Parse `imageUrl`.
2902 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2904 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2905 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2906 if (firstPartyCookiesEnabled) {
2907 // Get the cookies for `imageUrl`.
2908 String cookies = cookieManager.getCookie(imageUrl);
2910 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2911 downloadRequest.addRequestHeader("Cookie", cookies);
2914 // Get the file name from the dialog fragment.
2915 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2916 String imageName = downloadImageNameEditText.getText().toString();
2918 // Specify the download location.
2919 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2920 // Download to the public download directory.
2921 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2922 } else { // External write permission denied.
2923 // Download to the app's external download directory.
2924 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2927 // Allow `MediaScanner` to index the download if it is a media file.
2928 downloadRequest.allowScanningByMediaScanner();
2930 // Add the URL as the description for the download.
2931 downloadRequest.setDescription(imageUrl);
2933 // Show the download notification after the download is completed.
2934 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2936 // Remove the lint warning below that `downloadManager` might be `null`.
2937 assert downloadManager != null;
2939 // Initiate the download.
2940 downloadManager.enqueue(downloadRequest);
2941 } else { // The image is not an HTTP or HTTPS URI.
2942 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2947 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2948 // Download the file if it has an HTTP or HTTPS URI.
2949 if (downloadUrl.startsWith("http")) {
2950 // Get a handle for the system `DOWNLOAD_SERVICE`.
2951 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2953 // Parse `downloadUrl`.
2954 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2956 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2957 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2958 if (firstPartyCookiesEnabled) {
2959 // Get the cookies for `downloadUrl`.
2960 String cookies = cookieManager.getCookie(downloadUrl);
2962 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2963 downloadRequest.addRequestHeader("Cookie", cookies);
2966 // Get the file name from the dialog fragment.
2967 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2968 String fileName = downloadFileNameEditText.getText().toString();
2970 // Specify the download location.
2971 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2972 // Download to the public download directory.
2973 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2974 } else { // External write permission denied.
2975 // Download to the app's external download directory.
2976 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2979 // Allow `MediaScanner` to index the download if it is a media file.
2980 downloadRequest.allowScanningByMediaScanner();
2982 // Add the URL as the description for the download.
2983 downloadRequest.setDescription(downloadUrl);
2985 // Show the download notification after the download is completed.
2986 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2988 // Remove the lint warning below that `downloadManager` might be `null`.
2989 assert downloadManager != null;
2991 // Initiate the download.
2992 downloadManager.enqueue(downloadRequest);
2993 } else { // The download is not an HTTP or HTTPS URI.
2994 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2999 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3000 // Get handles for the views from `dialogFragment`.
3001 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3002 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3003 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3005 // Store the bookmark strings.
3006 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3007 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3009 // Update the bookmark.
3010 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3011 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3012 } else { // Update the bookmark using the `WebView` favorite icon.
3013 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3014 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3015 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3016 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3018 // Update the bookmark and the favorite icon.
3019 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3022 // Update `bookmarksCursor` with the current contents of this folder.
3023 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3025 // Update the `ListView`.
3026 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3030 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3031 // Get handles for the views from `dialogFragment`.
3032 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3033 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3034 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3035 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3037 // Get the new folder name.
3038 String newFolderNameString = editFolderNameEditText.getText().toString();
3040 // Check if the favorite icon has changed.
3041 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3042 // Update the name in the database.
3043 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3044 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3045 // Get the new folder icon `Bitmap`.
3046 Bitmap folderIconBitmap;
3047 if (defaultFolderIconRadioButton.isChecked()) {
3048 // Get the default folder icon and convert it to a `Bitmap`.
3049 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3050 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3051 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3052 } else { // Use the `WebView` favorite icon.
3053 folderIconBitmap = favoriteIconBitmap;
3056 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3057 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3058 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3059 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3061 // Update the folder icon in the database.
3062 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3063 } else { // The folder icon and the name have changed.
3064 // Get the new folder icon `Bitmap`.
3065 Bitmap folderIconBitmap;
3066 if (defaultFolderIconRadioButton.isChecked()) {
3067 // Get the default folder icon and convert it to a `Bitmap`.
3068 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3069 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3070 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3071 } else { // Use the `WebView` favorite icon.
3072 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3075 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3076 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3077 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3078 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3080 // Update the folder name and icon in the database.
3081 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3084 // Update `bookmarksCursor` with the current contents of this folder.
3085 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3087 // Update the `ListView`.
3088 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3092 public void onHttpAuthenticationCancel() {
3093 // Cancel the `HttpAuthHandler`.
3094 httpAuthHandler.cancel();
3098 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3099 // Get handles for the `EditTexts`.
3100 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3101 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3103 // Proceed with the HTTP authentication.
3104 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3107 public void viewSslCertificate(View view) {
3108 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3109 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3110 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3114 public void onSslErrorCancel() {
3115 sslErrorHandler.cancel();
3119 public void onSslErrorProceed() {
3120 sslErrorHandler.proceed();
3124 public void onSslMismatchBack() {
3125 if (mainWebView.canGoBack()) { // There is a back page in the history.
3126 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3127 navigatingHistory = true;
3130 mainWebView.goBack();
3131 } else { // There are no pages to go back to.
3132 // Load a blank page
3138 public void onSslMismatchProceed() {
3139 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3140 ignorePinnedSslCertificate = true;
3144 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3145 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3146 navigatingHistory = true;
3148 // Load the history entry.
3149 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3153 public void onClearHistory() {
3154 // Clear the history.
3155 mainWebView.clearHistory();
3158 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3160 public void onBackPressed() {
3161 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3162 // Close the navigation drawer.
3163 drawerLayout.closeDrawer(GravityCompat.START);
3164 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3165 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3166 // close the bookmarks drawer.
3167 drawerLayout.closeDrawer(GravityCompat.END);
3168 } else { // A subfolder is displayed.
3169 // Place the former parent folder in `currentFolder`.
3170 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3172 // Load the new folder.
3173 loadBookmarksFolder();
3176 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3177 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3178 navigatingHistory = true;
3181 mainWebView.goBack();
3182 } else { // There isn't anything to do in Privacy Browser.
3183 // Pass `onBackPressed()` to the system.
3184 super.onBackPressed();
3188 // 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.
3190 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3191 // File uploads only work on API >= 21.
3192 if (Build.VERSION.SDK_INT >= 21) {
3193 // Pass the file to the WebView.
3194 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3198 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3199 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3200 String unformattedUrlString = urlTextBox.getText().toString().trim();
3202 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3203 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3204 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3205 if (!unformattedUrlString.startsWith("http")) {
3206 unformattedUrlString = "http://" + unformattedUrlString;
3209 // Initialize `unformattedUrl`.
3210 URL unformattedUrl = null;
3212 // 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.
3214 unformattedUrl = new URL(unformattedUrlString);
3215 } catch (MalformedURLException e) {
3216 e.printStackTrace();
3219 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3220 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3221 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3222 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3223 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3224 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3227 Uri.Builder formattedUri = new Uri.Builder();
3228 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3230 // Decode `formattedUri` as a `String` in `UTF-8`.
3231 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3232 } else if (unformattedUrlString.isEmpty()){ // Load a blank web site.
3233 // Load a blank string.
3234 formattedUrlString = "";
3235 } else { // Search for the contents of the URL box.
3236 // Sanitize the search input and convert it to a search.
3237 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3239 // Add the base search URL.
3240 formattedUrlString = searchURL + encodedUrlString;
3243 // 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.
3244 urlTextBox.clearFocus();
3247 loadUrl(formattedUrlString);
3250 private void loadUrl(String url) {// Apply any custom domain settings.
3251 applyDomainSettings(url, true, false);
3253 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3254 urlIsLoading = true;
3257 mainWebView.loadUrl(url, customHeaders);
3260 public void findPreviousOnPage(View view) {
3261 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3262 mainWebView.findNext(false);
3265 public void findNextOnPage(View view) {
3266 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3267 mainWebView.findNext(true);
3270 public void closeFindOnPage(View view) {
3271 // Delete the contents of `find_on_page_edittext`.
3272 findOnPageEditText.setText(null);
3274 // Clear the highlighted phrases.
3275 mainWebView.clearMatches();
3277 // Hide the Find on Page `RelativeLayout`.
3278 findOnPageLinearLayout.setVisibility(View.GONE);
3280 // Show the URL app bar.
3281 supportAppBar.setVisibility(View.VISIBLE);
3283 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3284 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3287 private void applyAppSettings() {
3288 // Get a handle for the shared preferences.
3289 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3291 // Store the values from the shared preferences in variables.
3292 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3293 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3294 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3295 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3296 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3297 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3298 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3299 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3300 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3301 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3302 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3303 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3304 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3306 // Set the homepage, search, and proxy options.
3307 if (proxyThroughOrbot) { // Set the Tor options.
3308 // Set `torHomepageString` as `homepage`.
3309 homepage = torHomepageString;
3311 // If formattedUrlString is null assign the homepage to it.
3312 if (formattedUrlString == null) {
3313 formattedUrlString = homepage;
3316 // Set the search URL.
3317 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3318 searchURL = torSearchCustomURLString;
3319 } else { // Use the string from the pre-built list.
3320 searchURL = torSearchString;
3323 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3324 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3326 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3328 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3330 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3333 // Display a message to the user if we are waiting on Orbot.
3334 if (!orbotStatus.equals("ON")) {
3335 // Set `waitingForOrbot`.
3336 waitingForOrbot = true;
3338 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3339 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3341 } else { // Set the non-Tor options.
3342 // Set `homepageString` as `homepage`.
3343 homepage = homepageString;
3345 // If formattedUrlString is null assign the homepage to it.
3346 if (formattedUrlString == null) {
3347 formattedUrlString = homepage;
3350 // Set the search URL.
3351 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3352 searchURL = searchCustomURLString;
3353 } else { // Use the string from the pre-built list.
3354 searchURL = searchString;
3357 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3358 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3360 // Set the default `appBar` background. `this` refers to the context.
3362 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3364 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3367 // Reset `waitingForOrbot.
3368 waitingForOrbot = false;
3371 // Set Do Not Track status.
3372 if (doNotTrackEnabled) {
3373 customHeaders.put("DNT", "1");
3375 customHeaders.remove("DNT");
3378 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3379 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3380 if (hideSystemBarsOnFullscreen) { // Hide everything.
3381 // Remove the translucent navigation setting if it is currently flagged.
3382 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3384 // Remove the translucent status bar overlay.
3385 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3387 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3388 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3390 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3391 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3392 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3394 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3395 } else { // Hide everything except the status and navigation bars.
3396 // Add the translucent status flag if it is unset.
3397 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3399 if (translucentNavigationBarOnFullscreen) {
3400 // Set the navigation bar to be translucent.
3401 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3403 // Set the navigation bar to be black.
3404 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3407 } else { // Switch to normal viewing mode.
3408 // Reset `inFullScreenBrowsingMode` to `false`.
3409 inFullScreenBrowsingMode = false;
3411 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3412 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3416 // Show the `BannerAd` in the free flavor.
3417 if (BuildConfig.FLAVOR.contentEquals("free")) {
3418 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3419 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3422 // Remove the translucent navigation bar flag if it is set.
3423 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3425 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3426 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3428 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3429 rootCoordinatorLayout.setSystemUiVisibility(0);
3431 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3432 rootCoordinatorLayout.setFitsSystemWindows(true);
3436 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3437 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3438 @SuppressWarnings("deprecation")
3439 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3440 // Reset `navigatingHistory`.
3441 navigatingHistory = false;
3443 // Parse the URL into a URI.
3444 Uri uri = Uri.parse(url);
3446 // Extract the domain from `uri`.
3447 String hostName = uri.getHost();
3449 // Initialize `loadingNewDomainName`.
3450 boolean loadingNewDomainName;
3452 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3453 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3454 //noinspection SimplifiableIfStatement
3455 if ((hostName == null) || (currentDomainName == null)) {
3456 loadingNewDomainName = true;
3457 } else { // Determine if `hostName` equals `currentDomainName`.
3458 loadingNewDomainName = !hostName.equals(currentDomainName);
3461 // Strings don't like to be null.
3462 if (hostName == null) {
3466 // 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.
3467 if (loadingNewDomainName) {
3468 // Set the new `hostname` as the `currentDomainName`.
3469 currentDomainName = hostName;
3471 // Reset `ignorePinnedSslCertificate`.
3472 ignorePinnedSslCertificate = false;
3474 // Reset the favorite icon if specified.
3475 if (resetFavoriteIcon) {
3476 favoriteIconBitmap = favoriteIconDefaultBitmap;
3477 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3480 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3481 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3482 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3484 // Get a full cursor from `domainsDatabaseHelper`.
3485 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3487 // Initialize `domainSettingsSet`.
3488 Set<String> domainSettingsSet = new HashSet<>();
3490 // Get the domain name column index.
3491 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3493 // Populate `domainSettingsSet`.
3494 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3495 // Move `domainsCursor` to the current row.
3496 domainNameCursor.moveToPosition(i);
3498 // Store the domain name in `domainSettingsSet`.
3499 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3502 // Close `domainNameCursor.
3503 domainNameCursor.close();
3505 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3506 domainSettingsApplied = false;
3507 String domainNameInDatabase = null;
3509 // Check the hostname.
3510 if (domainSettingsSet.contains(hostName)) {
3511 domainSettingsApplied = true;
3512 domainNameInDatabase = hostName;
3515 // Check all the subdomains of the host name against wildcard domains in the domain cursor.
3516 while (!domainSettingsApplied && hostName.contains(".")) { // Stop checking if domain settings are already applied or there are no more `.` in the host name.
3517 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3518 // Apply the domain settings.
3519 domainSettingsApplied = true;
3521 // Store the applied domain names as it appears in the database.
3522 domainNameInDatabase = "*." + hostName;
3525 // Strip out the lowest subdomain of of the host name.
3526 hostName = hostName.substring(hostName.indexOf(".") + 1);
3530 // Get a handle for the shared preference.
3531 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3533 // Store the general preference information.
3534 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3535 String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3536 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3537 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3538 nightMode = sharedPreferences.getBoolean("night_mode", false);
3540 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3541 // Get a cursor for the current host and move it to the first position.
3542 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3543 currentHostDomainSettingsCursor.moveToFirst();
3545 // Get the settings from the cursor.
3546 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3547 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3548 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3549 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3550 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3551 // Form data can be removed once the minimum API >= 26.
3552 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3553 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3554 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3555 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3556 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3557 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3558 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3559 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3560 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3561 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3562 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3563 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3564 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3565 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3566 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3567 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3568 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3570 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3571 switch (nightModeInt) {
3572 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3576 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3581 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3583 javaScriptEnabled = true;
3586 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3587 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3588 pinnedDomainSslStartDate = null;
3590 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3593 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3594 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3595 pinnedDomainSslEndDate = null;
3597 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3600 // Close `currentHostDomainSettingsCursor`.
3601 currentHostDomainSettingsCursor.close();
3603 // Apply the domain settings.
3604 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3605 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3606 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3608 // Apply the form data setting if the API < 26.
3609 if (Build.VERSION.SDK_INT < 26) {
3610 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3613 // Apply the font size.
3614 if (fontSize == 0) { // Apply the default font size.
3615 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3616 } else { // Apply the specified font size.
3617 mainWebView.getSettings().setTextZoom(fontSize);
3620 // Set third-party cookies status if API >= 21.
3621 if (Build.VERSION.SDK_INT >= 21) {
3622 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3625 // 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.
3626 // <https://redmine.stoutner.com/issues/160>
3627 if (!urlIsLoading) {
3628 // Set the user agent.
3629 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3630 // Get the array position of the default user agent name.
3631 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3633 // Set the user agent according to the system default.
3634 switch (defaultUserAgentArrayPosition) {
3635 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3636 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3637 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3640 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3641 // Set the user agent to `""`, which uses the default value.
3642 mainWebView.getSettings().setUserAgentString("");
3645 case SETTINGS_CUSTOM_USER_AGENT:
3646 // Set the custom user agent.
3647 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3651 // Get the user agent string from the user agent data array
3652 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3654 } else { // Set the user agent according to the stored name.
3655 // Get the array position of the user agent name.
3656 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3658 switch (userAgentArrayPosition) {
3659 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3660 mainWebView.getSettings().setUserAgentString(userAgentName);
3663 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3664 // Set the user agent to `""`, which uses the default value.
3665 mainWebView.getSettings().setUserAgentString("");
3669 // Get the user agent string from the user agent data array.
3670 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3674 // Set swipe to refresh.
3675 switch (swipeToRefreshInt) {
3676 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3677 // Set swipe to refresh according to the default.
3678 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3681 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3682 // Enable swipe to refresh.
3683 swipeRefreshLayout.setEnabled(true);
3686 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3687 // Disable swipe to refresh.
3688 swipeRefreshLayout.setEnabled(false);
3691 // Store the applied user agent string, which is used in the View Source activity.
3692 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3695 // 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.
3697 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3699 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3701 } else { // The new URL does not have custom domain settings. Load the defaults.
3702 // Store the values from `sharedPreferences` in variables.
3703 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3704 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3705 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3706 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3707 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false); // Form data can be removed once the minimum API >= 26.
3708 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3709 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3710 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3711 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3713 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3715 javaScriptEnabled = true;
3718 // Apply the default settings.
3719 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3720 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3721 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3722 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3723 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3725 // Apply the form data setting if the API < 26.
3726 if (Build.VERSION.SDK_INT < 26) {
3727 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3730 // Reset the pinned SSL certificate information.
3731 domainSettingsDatabaseId = -1;
3732 pinnedDomainSslCertificate = false;
3733 pinnedDomainSslIssuedToCNameString = "";
3734 pinnedDomainSslIssuedToONameString = "";
3735 pinnedDomainSslIssuedToUNameString = "";
3736 pinnedDomainSslIssuedByCNameString = "";
3737 pinnedDomainSslIssuedByONameString = "";
3738 pinnedDomainSslIssuedByUNameString = "";
3739 pinnedDomainSslStartDate = null;
3740 pinnedDomainSslEndDate = null;
3742 // Set third-party cookies status if API >= 21.
3743 if (Build.VERSION.SDK_INT >= 21) {
3744 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3747 // 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.
3748 // <https://redmine.stoutner.com/issues/160>
3749 if (!urlIsLoading) {
3750 // Get the array position of the user agent name.
3751 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3753 // Set the user agent.
3754 switch (userAgentArrayPosition) {
3755 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3756 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3757 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3760 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3761 // Set the user agent to `""`, which uses the default value.
3762 mainWebView.getSettings().setUserAgentString("");
3765 case SETTINGS_CUSTOM_USER_AGENT:
3766 // Set the custom user agent.
3767 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3771 // Get the user agent string from the user agent data array
3772 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3775 // Store the applied user agent string, which is used in the View Source activity.
3776 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3779 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3780 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3783 // Close `domainsDatabaseHelper`.
3784 domainsDatabaseHelper.close();
3786 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3787 onTheFlyDisplayImagesSet = false;
3788 setDisplayWebpageImages();
3790 // Update the privacy icons, but only if `mainMenu` has already been populated.
3791 if (mainMenu != null) {
3792 updatePrivacyIcons(true);
3796 // Reload the website if returning from the Domains activity.
3797 if (reloadWebsite) {
3798 mainWebView.reload();
3802 private void setDisplayWebpageImages() {
3803 if (!onTheFlyDisplayImagesSet) {
3804 if (domainSettingsApplied) { // Custom domain settings are applied.
3805 switch (displayWebpageImagesInt) {
3806 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3807 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3810 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3811 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3814 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3815 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3818 } else { // Default settings are applied.
3819 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3824 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3825 // Get handles for the menu items.
3826 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3827 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3828 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3829 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
3831 // Update the privacy icon.
3832 if (javaScriptEnabled) { // JavaScript is enabled.
3833 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3834 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3835 privacyMenuItem.setIcon(R.drawable.warning);
3836 } else { // All the dangerous features are disabled.
3837 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3840 // Update the first-party cookies icon.
3841 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3842 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3843 } else { // First-party cookies are disabled.
3845 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3847 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3851 // Update the DOM storage icon.
3852 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3853 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3854 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3856 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3858 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3860 } else { // JavaScript is disabled, so DOM storage is ghosted.
3862 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3864 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3868 // Update the refresh icon.
3870 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3872 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3875 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3876 if (runInvalidateOptionsMenu) {
3877 invalidateOptionsMenu();
3881 private void highlightUrlText() {
3882 String urlString = urlTextBox.getText().toString();
3884 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3885 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3886 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3887 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3890 // Get the index of the `/` immediately after the domain name.
3891 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3893 // De-emphasize the text after the domain name.
3894 if (endOfDomainName > 0) {
3895 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3899 private void loadBookmarksFolder() {
3900 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
3901 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3903 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3904 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3906 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3907 // Inflate the individual item layout. `false` does not attach it to the root.
3908 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3912 public void bindView(View view, Context context, Cursor cursor) {
3913 // Get handles for the views.
3914 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3915 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3917 // Get the favorite icon byte array from the cursor.
3918 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3920 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3921 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3923 // Display the bitmap in `bookmarkFavoriteIcon`.
3924 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3926 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3927 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3928 bookmarkNameTextView.setText(bookmarkNameString);
3930 // Make the font bold for folders.
3931 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3932 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3933 } else { // Reset the font to default for normal bookmarks.
3934 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3939 // Populate the `ListView` with the adapter.
3940 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3942 // Set the bookmarks drawer title.
3943 if (currentBookmarksFolder.isEmpty()) {
3944 bookmarksTitleTextView.setText(R.string.bookmarks);
3946 bookmarksTitleTextView.setText(currentBookmarksFolder);