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 `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`,
158 // `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
159 // `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`,
160 // and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
161 public static boolean darkTheme;
163 // `allowScreenshots` is public static so it can be accessed from everywhere. It is also used in `onCreate()`.
164 public static boolean allowScreenshots;
166 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
167 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
168 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
169 public static Bitmap favoriteIconBitmap;
171 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
172 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
173 public static String formattedUrlString;
175 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
176 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
177 public static SslCertificate sslCertificate;
179 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
180 public static String orbotStatus;
182 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
183 public static String webViewTitle;
185 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
186 public static String appliedUserAgentString;
188 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
189 public static boolean reloadOnRestart;
191 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment` and `BookmarksActivity`. It is also used in `onRestart()`.
192 public static boolean loadUrlOnRestart;
194 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
195 public static boolean restartFromBookmarksActivity;
197 // The block list versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
198 public static String easyListVersion;
199 public static String easyPrivacyVersion;
200 public static String fanboyAnnoyanceVersion;
201 public static String fanboySocialVersion;
203 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
204 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
205 public static String currentBookmarksFolder;
207 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
208 public static int domainSettingsDatabaseId;
210 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
211 public static String pinnedDomainSslIssuedToCNameString;
212 public static String pinnedDomainSslIssuedToONameString;
213 public static String pinnedDomainSslIssuedToUNameString;
214 public static String pinnedDomainSslIssuedByCNameString;
215 public static String pinnedDomainSslIssuedByONameString;
216 public static String pinnedDomainSslIssuedByUNameString;
217 public static Date pinnedDomainSslStartDate;
218 public static Date pinnedDomainSslEndDate;
220 // The user agent constants are public static so they can be accessed from `SettingsFragment`, `DomainsActivity`, and `DomainSettingsFragment`.
221 public final static int UNRECOGNIZED_USER_AGENT = -1;
222 public final static int SETTINGS_WEBVIEW_DEFAULT_USER_AGENT = 1;
223 public final static int SETTINGS_CUSTOM_USER_AGENT = 12;
224 public final static int DOMAINS_SYSTEM_DEFAULT_USER_AGENT = 0;
225 public final static int DOMAINS_WEBVIEW_DEFAULT_USER_AGENT = 2;
226 public final static int DOMAINS_CUSTOM_USER_AGENT = 13;
229 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
230 private ActionBar appBar;
232 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
233 private boolean navigatingHistory;
235 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
236 private Bitmap favoriteIconDefaultBitmap;
238 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
239 private DrawerLayout drawerLayout;
241 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
242 private CoordinatorLayout rootCoordinatorLayout;
244 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
245 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
246 private WebView mainWebView;
248 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
249 private FrameLayout fullScreenVideoFrameLayout;
251 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsMenuSelected()`, and `onRestart()`.
252 private SwipeRefreshLayout swipeRefreshLayout;
254 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
255 private RelativeLayout urlAppBarRelativeLayout;
257 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
258 private ImageView favoriteIconImageView;
260 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
261 private CookieManager cookieManager;
263 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
264 private final Map<String, String> customHeaders = new HashMap<>();
266 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
267 private boolean javaScriptEnabled;
269 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
270 private boolean firstPartyCookiesEnabled;
272 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
273 private boolean thirdPartyCookiesEnabled;
275 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
276 private boolean domStorageEnabled;
278 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
279 private boolean saveFormDataEnabled;
281 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
282 private boolean nightMode;
284 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
285 private boolean displayWebpageImagesBoolean;
287 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
288 private String homepage;
290 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
291 private String searchURL;
293 // The block list variables are used in `onCreate()` and `applyAppSettings()`.
294 private boolean easyListEnabled;
295 private boolean easyPrivacyEnabled;
296 private boolean fanboysAnnoyanceListEnabled;
297 private boolean fanboysSocialBlockingListEnabled;
299 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
300 private Runtime privacyBrowserRuntime;
302 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
303 private boolean proxyThroughOrbot;
305 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
306 private boolean incognitoModeEnabled;
308 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
309 private boolean fullScreenBrowsingModeEnabled;
311 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
312 private boolean inFullScreenBrowsingMode;
314 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
315 private boolean hideSystemBarsOnFullscreen;
317 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
318 private boolean translucentNavigationBarOnFullscreen;
320 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
321 private boolean reapplyDomainSettingsOnRestart;
323 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
324 private boolean reapplyAppSettingsOnRestart;
326 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
327 private String currentDomainName;
329 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
330 private boolean ignorePinnedSslCertificate;
332 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
333 private boolean waitingForOrbot;
335 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
336 private boolean domainSettingsApplied;
338 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
339 private int displayWebpageImagesInt;
341 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
342 private boolean onTheFlyDisplayImagesSet;
344 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
345 private String waitingForOrbotHTMLString;
347 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
348 private String privateDataDirectoryString;
350 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
351 private LinearLayout findOnPageLinearLayout;
353 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
354 private EditText findOnPageEditText;
356 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
357 private Menu mainMenu;
359 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
360 private ActionBarDrawerToggle drawerToggle;
362 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
363 private Toolbar supportAppBar;
365 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
366 private EditText urlTextBox;
368 // The color spans are used in `onCreate()` and `highlightUrlText()`.
369 private ForegroundColorSpan redColorSpan;
370 private ForegroundColorSpan initialGrayColorSpan;
371 private ForegroundColorSpan finalGrayColorSpan;
373 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
374 private SslErrorHandler sslErrorHandler;
376 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
377 private static HttpAuthHandler httpAuthHandler;
379 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
380 private InputMethodManager inputMethodManager;
382 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
383 private RelativeLayout mainWebViewRelativeLayout;
385 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
386 private boolean urlIsLoading;
388 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
389 private boolean pinnedDomainSslCertificate;
391 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
392 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
394 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
395 private ListView bookmarksListView;
397 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
398 private TextView bookmarksTitleTextView;
400 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
401 private Cursor bookmarksCursor;
403 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
404 private CursorAdapter bookmarksCursorAdapter;
406 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
407 private String oldFolderNameString;
409 // `fileChooserCallback` is used in `onCreate()` and `onActivityResult()`.
410 private ValueCallback<Uri[]> fileChooserCallback;
412 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
413 private String downloadUrl;
414 private String downloadContentDisposition;
415 private long downloadContentLength;
417 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
418 private String downloadImageUrl;
420 // The user agent variables are used in `onCreate()` and `applyDomainSettings()`.
421 private ArrayAdapter<CharSequence> userAgentNamesArray;
422 private String[] userAgentDataArray;
424 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
425 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
426 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
429 // 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.
430 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
431 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
432 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
433 @SuppressWarnings("deprecation")
434 protected void onCreate(Bundle savedInstanceState) {
435 // Get a handle for the shared preferences.
436 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
438 // Get the theme and screenshot preferences.
439 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
440 allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
442 // Disable screenshots if not allowed.
443 if (!allowScreenshots) {
444 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
447 // Set the activity theme.
449 setTheme(R.style.PrivacyBrowserDark);
451 setTheme(R.style.PrivacyBrowserLight);
454 // Run the default commands.
455 super.onCreate(savedInstanceState);
457 // Set the content view.
458 setContentView(R.layout.main_drawerlayout);
460 // Get a handle for `inputMethodManager`.
461 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
463 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
464 supportAppBar = findViewById(R.id.app_bar);
465 setSupportActionBar(supportAppBar);
466 appBar = getSupportActionBar();
468 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
469 assert appBar != null;
471 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
472 appBar.setCustomView(R.layout.url_app_bar);
473 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
475 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
476 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
477 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
478 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
480 // Get a handle for `urlTextBox`.
481 urlTextBox = findViewById(R.id.url_edittext);
483 // Remove the formatting from `urlTextBar` when the user is editing the text.
484 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
485 if (hasFocus) { // The user is editing `urlTextBox`.
486 // Remove the highlighting.
487 urlTextBox.getText().removeSpan(redColorSpan);
488 urlTextBox.getText().removeSpan(initialGrayColorSpan);
489 urlTextBox.getText().removeSpan(finalGrayColorSpan);
490 } else { // The user has stopped editing `urlTextBox`.
491 // Reapply the highlighting.
496 // Set the go button on the keyboard to load the URL in `urlTextBox`.
497 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
498 // If the event is a key-down event on the `enter` button, load the URL.
499 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
500 // Load the URL into the mainWebView and consume the event.
502 loadUrlFromTextBox();
503 } catch (UnsupportedEncodingException e) {
506 // If the enter key was pressed, consume the event.
509 // If any other key was pressed, do not consume the event.
514 // Set `waitingForOrbotHTMLString`.
515 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
517 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
518 currentDomainName = "";
519 orbotStatus = "unknown";
520 waitingForOrbot = false;
522 // Create an Orbot status `BroadcastReceiver`.
523 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
525 public void onReceive(Context context, Intent intent) {
526 // Store the content of the status message in `orbotStatus`.
527 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
529 // If we are waiting on Orbot, load the website now that Orbot is connected.
530 if (orbotStatus.equals("ON") && waitingForOrbot) {
531 // Reset `waitingForOrbot`.
532 waitingForOrbot = false;
534 // Load `formattedUrlString
535 loadUrl(formattedUrlString);
540 // Register `orbotStatusBroadcastReceiver` on `this` context.
541 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
543 // Get handles for views that need to be accessed.
544 drawerLayout = findViewById(R.id.drawerlayout);
545 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
546 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
547 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
548 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
549 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
550 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
551 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
552 mainWebView = findViewById(R.id.main_webview);
553 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
554 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
555 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
556 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
557 favoriteIconImageView = findViewById(R.id.favorite_icon);
559 // 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.
561 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
562 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
563 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
564 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
566 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
567 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
568 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
569 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
572 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
573 launchBookmarksActivityFab.setOnClickListener(v -> {
574 // Create an intent to launch the bookmarks activity.
575 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
577 // Include the current folder with the `Intent`.
578 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
581 startActivity(bookmarksIntent);
584 // Set the create new bookmark folder FAB to display an alert dialog.
585 createBookmarkFolderFab.setOnClickListener(v -> {
586 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
587 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
588 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
591 // Set the create new bookmark FAB to display an alert dialog.
592 createBookmarkFab.setOnClickListener(view -> {
593 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
594 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
595 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
598 // Create a double-tap listener to toggle full-screen mode.
599 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
600 // Override `onDoubleTap()`. All other events are handled using the default settings.
602 public boolean onDoubleTap(MotionEvent event) {
603 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
604 // Toggle `inFullScreenBrowsingMode`.
605 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
607 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
608 // Hide the `appBar`.
611 // Hide the banner ad in the free flavor.
612 if (BuildConfig.FLAVOR.contentEquals("free")) {
613 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
614 AdHelper.hideAd(findViewById(R.id.adview));
617 // Modify the system bars.
618 if (hideSystemBarsOnFullscreen) { // Hide everything.
619 // Remove the translucent overlays.
620 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
622 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
623 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
625 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
626 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
627 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
629 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
631 // Set `rootCoordinatorLayout` to fill the whole screen.
632 rootCoordinatorLayout.setFitsSystemWindows(false);
633 } else { // Hide everything except the status and navigation bars.
634 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
635 rootCoordinatorLayout.setFitsSystemWindows(false);
637 // 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.
638 if (translucentNavigationBarOnFullscreen) {
639 // Set the navigation bar to be translucent.
640 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
643 } else { // Switch to normal viewing mode.
644 // Show the `appBar`.
647 // Show the `BannerAd` in the free flavor.
648 if (BuildConfig.FLAVOR.contentEquals("free")) {
649 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
650 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
653 // Remove the translucent navigation bar flag if it is set.
654 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
656 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
657 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
659 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
660 rootCoordinatorLayout.setSystemUiVisibility(0);
662 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
663 rootCoordinatorLayout.setFitsSystemWindows(true);
666 // Consume the double-tap.
668 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
674 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
675 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
676 // Call `performClick()` on the view, which is required for accessibility.
679 // Send the `event` to `gestureDetector`.
680 return gestureDetector.onTouchEvent(event);
683 // Update `findOnPageCountTextView`.
684 mainWebView.setFindListener(new WebView.FindListener() {
685 // Get a handle for `findOnPageCountTextView`.
686 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
689 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
690 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
691 // Set `findOnPageCountTextView` to `0/0`.
692 findOnPageCountTextView.setText(R.string.zero_of_zero);
693 } else if (isDoneCounting) { // There are matches.
694 // `activeMatchOrdinal` is zero-based.
695 int activeMatch = activeMatchOrdinal + 1;
697 // Build the match string.
698 String matchString = activeMatch + "/" + numberOfMatches;
700 // Set `findOnPageCountTextView`.
701 findOnPageCountTextView.setText(matchString);
706 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
707 findOnPageEditText.addTextChangedListener(new TextWatcher() {
709 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
714 public void onTextChanged(CharSequence s, int start, int before, int count) {
719 public void afterTextChanged(Editable s) {
720 // Search for the text in `mainWebView`.
721 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
725 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
726 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
727 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
728 // Hide the soft keyboard. `0` indicates no additional flags.
729 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
731 // Consume the event.
733 } else { // A different key was pressed.
734 // Do not consume the event.
739 // Implement swipe to refresh
740 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
741 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
742 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
744 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
745 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
746 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
748 // Listen for touches on the navigation menu.
749 final NavigationView navigationView = findViewById(R.id.navigationview);
750 navigationView.setNavigationItemSelectedListener(this);
752 // 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.
753 final Menu navigationMenu = navigationView.getMenu();
754 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
755 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
756 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
758 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
759 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
760 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
762 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
763 currentBookmarksFolder = "";
765 // Load the home folder, which is `""` in the database.
766 loadBookmarksFolder();
768 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
769 // Convert the id from long to int to match the format of the bookmarks database.
770 int databaseID = (int) id;
772 // Get the bookmark cursor for this ID and move it to the first row.
773 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
774 bookmarkCursor.moveToFirst();
776 // Act upon the bookmark according to the type.
777 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
778 // Store the new folder name in `currentBookmarksFolder`.
779 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
781 // Load the new folder.
782 loadBookmarksFolder();
783 } else { // The selected bookmark is not a folder.
784 // Load the bookmark URL.
785 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
787 // Close the bookmarks drawer.
788 drawerLayout.closeDrawer(GravityCompat.END);
791 // Close the `Cursor`.
792 bookmarkCursor.close();
795 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
796 // Convert the database ID from `long` to `int`.
797 int databaseId = (int) id;
799 // Find out if the selected bookmark is a folder.
800 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
803 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
804 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
806 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
807 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
808 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
810 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
811 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
812 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
815 // Consume the event.
819 // The `DrawerListener` allows us to update the Navigation Menu.
820 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
822 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
826 public void onDrawerOpened(@NonNull View drawerView) {
830 public void onDrawerClosed(@NonNull View drawerView) {
834 public void onDrawerStateChanged(int newState) {
835 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
836 // Update the `Back`, `Forward`, and `History` menu items.
837 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
838 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
839 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
841 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
842 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
844 // Clear the focus from `urlTextBox` if it has it.
845 urlTextBox.clearFocus();
850 // drawerToggle creates the hamburger icon at the start of the AppBar.
851 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
853 // Get a handle for the progress bar.
854 final ProgressBar progressBar = findViewById(R.id.progress_bar);
856 mainWebView.setWebChromeClient(new WebChromeClient() {
857 // Update the progress bar when a page is loading.
859 public void onProgressChanged(WebView view, int progress) {
860 // Inject the night mode CSS if night mode is enabled.
862 // `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
863 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
864 // `border: none` removes all borders, which can also be used to underline text.
865 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
866 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
867 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
868 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
869 // Initialize a `Handler` to display `mainWebView`.
870 Handler displayWebViewHandler = new Handler();
872 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
873 Runnable displayWebViewRunnable = () -> {
874 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
875 if (progressBar.getVisibility() == View.GONE) {
876 mainWebView.setVisibility(View.VISIBLE);
880 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
881 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
885 // Update the progress bar.
886 progressBar.setProgress(progress);
888 // Set the visibility of the progress bar.
889 if (progress < 100) {
890 // Show the progress bar.
891 progressBar.setVisibility(View.VISIBLE);
893 // Hide the progress bar.
894 progressBar.setVisibility(View.GONE);
896 // Display `mainWebView` if night mode is disabled.
897 // 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
898 // currently enabled.
900 mainWebView.setVisibility(View.VISIBLE);
903 //Stop the swipe to refresh indicator if it is running
904 swipeRefreshLayout.setRefreshing(false);
908 // Set the favorite icon when it changes.
910 public void onReceivedIcon(WebView view, Bitmap icon) {
911 // Only update the favorite icon if the website has finished loading.
912 if (progressBar.getVisibility() == View.GONE) {
913 // Save a copy of the favorite icon.
914 favoriteIconBitmap = icon;
916 // Place the favorite icon in the appBar.
917 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
921 // Save a copy of the title when it changes.
923 public void onReceivedTitle(WebView view, String title) {
924 // Save a copy of the title.
925 webViewTitle = title;
928 // Enter full screen video.
930 public void onShowCustomView(View view, CustomViewCallback callback) {
931 // Pause the ad if this is the free flavor.
932 if (BuildConfig.FLAVOR.contentEquals("free")) {
933 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
934 AdHelper.pauseAd(findViewById(R.id.adview));
937 // Remove the translucent overlays.
938 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
940 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
941 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
943 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
944 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
945 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
947 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
949 // Set `rootCoordinatorLayout` to fill the entire screen.
950 rootCoordinatorLayout.setFitsSystemWindows(false);
952 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
953 fullScreenVideoFrameLayout.addView(view);
954 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
957 // Exit full screen video.
959 public void onHideCustomView() {
960 // Hide `fullScreenVideoFrameLayout`.
961 fullScreenVideoFrameLayout.removeAllViews();
962 fullScreenVideoFrameLayout.setVisibility(View.GONE);
964 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
965 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
967 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
968 rootCoordinatorLayout.setFitsSystemWindows(true);
970 // Show the ad if this is the free flavor.
971 if (BuildConfig.FLAVOR.contentEquals("free")) {
972 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
973 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
979 public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
980 // Show the file chooser if the device is running API >= 21.
981 if (Build.VERSION.SDK_INT >= 21) {
982 // Store the file path callback.
983 fileChooserCallback = filePathCallback;
985 // Create an intent to open a chooser based ont the file chooser parameters.
986 Intent fileChooserIntent = fileChooserParams.createIntent();
988 // Open the file chooser. Currently only one `startActivityForResult` exists in this activity, so the request code, used to differentiate them, is simply `0`.
989 startActivityForResult(fileChooserIntent, 0);
995 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
996 registerForContextMenu(mainWebView);
998 // Allow the downloading of files.
999 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1000 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
1001 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
1002 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
1004 // Store the variables for future use by `onRequestPermissionsResult()`.
1006 downloadContentDisposition = contentDisposition;
1007 downloadContentLength = contentLength;
1009 // Show a dialog if the user has previously denied the permission.
1010 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
1011 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
1012 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
1014 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
1015 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
1016 } else { // Show the permission request directly.
1017 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
1018 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
1020 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
1021 // Get a handle for the download file alert dialog.
1022 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1024 // Show the download file alert dialog.
1025 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1029 // Allow pinch to zoom.
1030 mainWebView.getSettings().setBuiltInZoomControls(true);
1032 // Hide zoom controls.
1033 mainWebView.getSettings().setDisplayZoomControls(false);
1035 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1036 mainWebView.getSettings().setUseWideViewPort(true);
1038 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1039 mainWebView.getSettings().setLoadWithOverviewMode(true);
1041 // Explicitly disable geolocation.
1042 mainWebView.getSettings().setGeolocationEnabled(false);
1044 // Initialize cookieManager.
1045 cookieManager = CookieManager.getInstance();
1047 // 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).
1048 customHeaders.put("X-Requested-With", "");
1050 // 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.
1051 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1053 // Get the intent that started the app.
1054 final Intent launchingIntent = getIntent();
1056 // Extract the launching intent data as `launchingIntentUriData`.
1057 final Uri launchingIntentUriData = launchingIntent.getData();
1059 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1060 if (launchingIntentUriData != null) {
1061 formattedUrlString = launchingIntentUriData.toString();
1064 // Get a handle for the `Runtime`.
1065 privacyBrowserRuntime = Runtime.getRuntime();
1067 // Store the application's private data directory.
1068 privateDataDirectoryString = getApplicationInfo().dataDir;
1069 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1071 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1072 inFullScreenBrowsingMode = false;
1074 // Initialize the privacy settings variables.
1075 javaScriptEnabled = false;
1076 firstPartyCookiesEnabled = false;
1077 thirdPartyCookiesEnabled = false;
1078 domStorageEnabled = false;
1079 saveFormDataEnabled = false;
1082 // Initialize the WebView title.
1083 webViewTitle = getString(R.string.no_title);
1085 // Initialize the favorite icon bitmap. `ContextCompat` must be used until API >= 21.
1086 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1087 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1088 assert favoriteIconBitmapDrawable != null;
1089 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1091 // If the favorite icon is null, load the default.
1092 if (favoriteIconBitmap == null) {
1093 favoriteIconBitmap = favoriteIconDefaultBitmap;
1096 // Initialize the user agent array adapter and string array.
1097 userAgentNamesArray = ArrayAdapter.createFromResource(this, R.array.user_agent_names, R.layout.domain_settings_spinner_item);
1098 userAgentDataArray = getResources().getStringArray(R.array.user_agent_data);
1100 // Apply the app settings from the shared preferences.
1103 // Instantiate the block list helper.
1104 BlockListHelper blockListHelper = new BlockListHelper();
1106 // Parse the block lists.
1107 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1108 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1109 final ArrayList<List<String[]>> fanboyAnnoyance = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1110 final ArrayList<List<String[]>> fanboySocial = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1112 // Store the list versions.
1113 easyListVersion = easyList.get(0).get(0)[0];
1114 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1115 fanboyAnnoyanceVersion = fanboyAnnoyance.get(0).get(0)[0];
1116 fanboySocialVersion = fanboySocial.get(0).get(0)[0];
1118 mainWebView.setWebViewClient(new WebViewClient() {
1119 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1120 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1121 @SuppressWarnings("deprecation")
1123 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1124 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1125 // Apply the domain settings for the new URL.
1126 applyDomainSettings(url, true, false);
1128 // Returning false causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
1130 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1131 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1132 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1134 // Parse the url and set it as the data for the intent.
1135 emailIntent.setData(Uri.parse(url));
1137 // Open the email program in a new task instead of as part of Privacy Browser.
1138 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1141 startActivity(emailIntent);
1143 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1145 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1146 // Open the dialer and load the phone number, but wait for the user to place the call.
1147 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1149 // Add the phone number to the intent.
1150 dialIntent.setData(Uri.parse(url));
1152 // Open the dialer in a new task instead of as part of Privacy Browser.
1153 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1156 startActivity(dialIntent);
1158 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1160 } else { // Load a system chooser to select an app that can handle the URL.
1161 // Open an app that can handle the URL.
1162 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1164 // Add the URL to the intent.
1165 genericIntent.setData(Uri.parse(url));
1167 // List all apps that can handle the URL instead of just opening the first one.
1168 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1170 // Open the app in a new task instead of as part of Privacy Browser.
1171 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1173 // Start the app or display a snackbar if no app is available to handle the URL.
1175 startActivity(genericIntent);
1176 } catch (ActivityNotFoundException exception) {
1177 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1180 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1185 // Check requests against the block lists. The deprecated `shouldInterceptRequest` must be used until minimum API >= 21.
1186 @SuppressWarnings("deprecation")
1188 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1189 // Create an empty web resource response to be used if the resource request is blocked.
1190 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1192 // Check EasyList if it is enabled.
1193 if (easyListEnabled) {
1194 if (blockListHelper.isBlocked(formattedUrlString, url, easyList)) {
1195 // The resource request was blocked. Return an empty web resource response.
1196 return emptyWebResourceResponse;
1200 // Check EasyPrivacy if it is enabled.
1201 if (easyPrivacyEnabled) {
1202 if (blockListHelper.isBlocked(formattedUrlString, url, easyPrivacy)) {
1203 // The resource request was blocked. Return an empty web resource response.
1204 return emptyWebResourceResponse;
1208 // Check Fanboy’s Annoyance List if it is enabled.
1209 if (fanboysAnnoyanceListEnabled) {
1210 if (blockListHelper.isBlocked(formattedUrlString, url, fanboyAnnoyance)) {
1211 // The resource request was blocked. Return an empty web resource response.
1212 return emptyWebResourceResponse;
1214 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1215 if (blockListHelper.isBlocked(formattedUrlString, url, fanboySocial)) {
1216 // The resource request was blocked. Return an empty web resource response.
1217 return emptyWebResourceResponse;
1221 // The resource request has not been blocked. `return null` loads the requested resource.
1225 // Handle HTTP authentication requests.
1227 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1228 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1229 httpAuthHandler = handler;
1231 // Display the HTTP authentication dialog.
1232 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1233 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1236 // Update the URL in urlTextBox when the page starts to load.
1238 public void onPageStarted(WebView view, String url, Bitmap favicon) {// If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1240 mainWebView.setVisibility(View.INVISIBLE);
1243 // Hide the keyboard. `0` indicates no additional flags.
1244 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1246 // Check to see if we are waiting on Orbot.
1247 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1248 // 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.
1249 formattedUrlString = url;
1251 // Display the formatted URL text.
1252 urlTextBox.setText(formattedUrlString);
1254 // Apply text highlighting to `urlTextBox`.
1257 // Apply any custom domain settings if the URL was loaded by navigating history.
1258 if (navigatingHistory) {
1259 applyDomainSettings(url, true, false);
1262 // 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.
1263 urlIsLoading = true;
1267 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1269 public void onPageFinished(WebView view, String url) {
1270 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1271 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1272 cookieManager.flush();
1275 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1276 urlIsLoading = false;
1278 // Clear the cache and history if Incognito Mode is enabled.
1279 if (incognitoModeEnabled) {
1280 // Clear the cache. `true` includes disk files.
1281 mainWebView.clearCache(true);
1283 // Clear the back/forward history.
1284 mainWebView.clearHistory();
1286 // Manually delete cache folders.
1288 // Delete the main cache directory.
1289 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1291 // Delete the secondary `Service Worker` cache directory.
1292 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1293 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1294 } catch (IOException e) {
1295 // Do nothing if an error is thrown.
1299 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1300 if (!waitingForOrbot) {
1301 // Check to see if `WebView` has set `url` to be `about:blank`.
1302 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1303 // Set `formattedUrlString` to `""`.
1304 formattedUrlString = "";
1306 urlTextBox.setText(formattedUrlString);
1308 // Request focus for `urlTextBox`.
1309 urlTextBox.requestFocus();
1311 // Display the keyboard.
1312 inputMethodManager.showSoftInput(urlTextBox, 0);
1314 // Apply the domain settings. This clears any settings from the previous domain.
1315 applyDomainSettings(formattedUrlString, true, false);
1316 } else { // `WebView` has loaded a webpage.
1317 // Set `formattedUrlString`.
1318 formattedUrlString = url;
1320 // Only update `urlTextBox` if the user is not typing in it.
1321 if (!urlTextBox.hasFocus()) {
1322 // Display the formatted URL text.
1323 urlTextBox.setText(formattedUrlString);
1325 // Apply text highlighting to `urlTextBox`.
1330 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1331 sslCertificate = mainWebView.getCertificate();
1333 // 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.
1334 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1335 // Initialize the current SSL certificate variables.
1336 String currentWebsiteIssuedToCName = "";
1337 String currentWebsiteIssuedToOName = "";
1338 String currentWebsiteIssuedToUName = "";
1339 String currentWebsiteIssuedByCName = "";
1340 String currentWebsiteIssuedByOName = "";
1341 String currentWebsiteIssuedByUName = "";
1342 Date currentWebsiteSslStartDate = null;
1343 Date currentWebsiteSslEndDate = null;
1346 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1347 if (sslCertificate != null) {
1348 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1349 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1350 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1351 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1352 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1353 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1354 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1355 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1358 // 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`.
1359 String currentWebsiteSslStartDateString = "";
1360 String currentWebsiteSslEndDateString = "";
1361 String pinnedDomainSslStartDateString = "";
1362 String pinnedDomainSslEndDateString = "";
1364 // Convert the `Dates` to `Strings` if they are not `null`.
1365 if (currentWebsiteSslStartDate != null) {
1366 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1369 if (currentWebsiteSslEndDate != null) {
1370 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1373 if (pinnedDomainSslStartDate != null) {
1374 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1377 if (pinnedDomainSslEndDate != null) {
1378 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1381 // Check to see if the pinned SSL certificate matches the current website certificate.
1382 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1383 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1384 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1385 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1386 // The pinned SSL certificate doesn't match the current domain certificate.
1387 //Display the pinned SSL certificate mismatch `AlertDialog`.
1388 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1389 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1395 // Handle SSL Certificate errors.
1397 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1398 // Get the current website SSL certificate.
1399 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1401 // Extract the individual pieces of information from the current website SSL certificate.
1402 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1403 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1404 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1405 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1406 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1407 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1408 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1409 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1411 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1412 if (pinnedDomainSslCertificate &&
1413 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1414 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1415 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1416 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1417 // An SSL certificate is pinned and matches the current domain certificate.
1418 // Proceed to the website without displaying an error.
1420 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1421 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1422 sslErrorHandler = handler;
1424 // Display the SSL error `AlertDialog`.
1425 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1426 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1431 // Load the website if not waiting for Orbot to connect.
1432 if (!waitingForOrbot) {
1433 loadUrl(formattedUrlString);
1438 protected void onNewIntent(Intent intent) {
1439 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1442 // Check to see if the intent contains a new URL.
1443 if (intent.getData() != null) {
1444 // Get the intent data and convert it to a string.
1445 final Uri intentUriData = intent.getData();
1446 formattedUrlString = intentUriData.toString();
1448 // Load the website.
1449 loadUrl(formattedUrlString);
1451 // Close the navigation drawer if it is open.
1452 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1453 drawerLayout.closeDrawer(GravityCompat.START);
1456 // Close the bookmarks drawer if it is open.
1457 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1458 drawerLayout.closeDrawer(GravityCompat.END);
1461 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1462 mainWebView.requestFocus();
1467 public void onRestart() {
1468 // Run the default commands.
1471 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1472 if (proxyThroughOrbot) {
1473 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1474 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1476 // Send the intent to the Orbot package.
1477 orbotIntent.setPackage("org.torproject.android");
1480 sendBroadcast(orbotIntent);
1483 // Apply the app settings if returning from the Settings activity..
1484 if (reapplyAppSettingsOnRestart) {
1485 // Apply the app settings.
1488 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1489 if (reloadOnRestart) {
1490 // Reload `mainWebView`.
1491 mainWebView.reload();
1493 // Reset `reloadOnRestartBoolean`.
1494 reloadOnRestart = false;
1497 // Reset the return from settings flag.
1498 reapplyAppSettingsOnRestart = false;
1501 // Apply the domain settings if returning from the Domains activity.
1502 if (reapplyDomainSettingsOnRestart) {
1503 // Reapply the domain settings.
1504 applyDomainSettings(formattedUrlString, false, true);
1506 // Reset `reapplyDomainSettingsOnRestart`.
1507 reapplyDomainSettingsOnRestart = false;
1510 // Load the URL on restart to apply changes to night mode.
1511 if (loadUrlOnRestart) {
1512 // Load the current `formattedUrlString`.
1513 loadUrl(formattedUrlString);
1515 // Reset `loadUrlOnRestart.
1516 loadUrlOnRestart = false;
1519 // Update the bookmarks drawer if returning from the Bookmarks activity.
1520 if (restartFromBookmarksActivity) {
1521 // Close the bookmarks drawer.
1522 drawerLayout.closeDrawer(GravityCompat.END);
1524 // Reload the bookmarks drawer.
1525 loadBookmarksFolder();
1527 // Reset `restartFromBookmarksActivity`.
1528 restartFromBookmarksActivity = false;
1531 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1532 updatePrivacyIcons(true);
1535 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1537 public void onResume() {
1538 // Run the default commands.
1541 // Resume JavaScript (if enabled).
1542 mainWebView.resumeTimers();
1544 // Resume `mainWebView`.
1545 mainWebView.onResume();
1547 // Resume the adView for the free flavor.
1548 if (BuildConfig.FLAVOR.contentEquals("free")) {
1549 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1550 AdHelper.resumeAd(findViewById(R.id.adview));
1555 public void onPause() {
1556 // Pause `mainWebView`.
1557 mainWebView.onPause();
1559 // Stop all JavaScript.
1560 mainWebView.pauseTimers();
1562 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1563 if (BuildConfig.FLAVOR.contentEquals("free")) {
1564 // The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
1565 AdHelper.pauseAd(findViewById(R.id.adview));
1572 public boolean onCreateOptionsMenu(Menu menu) {
1573 // Inflate the menu; this adds items to the action bar if it is present.
1574 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1576 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1579 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1580 updatePrivacyIcons(false);
1582 // Get handles for the menu items.
1583 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1584 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1585 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1586 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1588 // Only display third-party cookies if SDK >= 21
1589 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1591 // Get the shared preference values. `this` references the current context.
1592 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1594 // 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.
1595 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1596 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1597 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1598 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
1599 } else { //Do not display the additional icons.
1600 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1601 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1602 refreshMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1609 public boolean onPrepareOptionsMenu(Menu menu) {
1610 // Get handles for the menu items.
1611 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1612 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1613 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1614 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1615 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1616 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1617 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1618 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1619 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1620 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1621 MenuItem swipeToRefreshMenuItem = menu.findItem(R.id.swipe_to_refresh);
1622 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1623 MenuItem adConsentMenuItem = menu.findItem(R.id.ad_consent);
1625 // Set the text for the domain menu item.
1626 if (domainSettingsApplied) {
1627 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1629 addOrEditDomain.setTitle(R.string.add_domain_settings);
1632 // Set the status of the menu item checkboxes.
1633 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1634 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1635 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1636 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1637 swipeToRefreshMenuItem.setChecked(swipeRefreshLayout.isEnabled());
1638 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1640 // Enable third-party cookies if first-party cookies are enabled.
1641 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1643 // Enable `DOM Storage` if JavaScript is enabled.
1644 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1646 // Enable `Clear Cookies` if there are any.
1647 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1649 // Get a count of the number of files in the `Local Storage` directory.
1650 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1651 int localStorageDirectoryNumberOfFiles = 0;
1652 if (localStorageDirectory.exists()) {
1653 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1656 // Get a count of the number of files in the `IndexedDB` directory.
1657 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1658 int indexedDBDirectoryNumberOfFiles = 0;
1659 if (indexedDBDirectory.exists()) {
1660 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1663 // Enable `Clear DOM Storage` if there is any.
1664 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1666 // Enable `Clear Form Data` is there is any.
1667 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1668 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1670 // Enable `Clear Data` if any of the submenu items are enabled.
1671 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1673 // Initialize font size variables.
1674 int fontSize = mainWebView.getSettings().getTextZoom();
1675 String fontSizeTitle;
1676 MenuItem selectedFontSizeMenuItem;
1678 // Prepare the font size title and current size menu item.
1681 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1682 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1686 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1687 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1691 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1692 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1696 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1697 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1701 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1702 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1706 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1707 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1711 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1712 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1716 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1717 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1721 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1722 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1726 // Set the font size title and select the current size menu item.
1727 fontSizeMenuItem.setTitle(fontSizeTitle);
1728 selectedFontSizeMenuItem.setChecked(true);
1730 // Only show Ad Consent if this is the free flavor.
1731 adConsentMenuItem.setVisible(BuildConfig.FLAVOR.contentEquals("free"));
1733 // Run all the other default commands.
1734 super.onPrepareOptionsMenu(menu);
1736 // Display the menu.
1741 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1742 @SuppressLint("SetJavaScriptEnabled")
1743 // removeAllCookies is deprecated, but it is required for API < 21.
1744 @SuppressWarnings("deprecation")
1745 public boolean onOptionsItemSelected(MenuItem menuItem) {
1746 // Get the selected menu item ID.
1747 int menuItemId = menuItem.getItemId();
1749 // Set the commands that relate to the menu entries.
1750 switch (menuItemId) {
1751 case R.id.toggle_javascript:
1752 // Switch the status of javaScriptEnabled.
1753 javaScriptEnabled = !javaScriptEnabled;
1755 // Apply the new JavaScript status.
1756 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1758 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1759 updatePrivacyIcons(true);
1761 // Display a `Snackbar`.
1762 if (javaScriptEnabled) { // JavaScrip is enabled.
1763 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1764 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1765 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1766 } else { // Privacy mode.
1767 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1770 // Reload the WebView.
1771 mainWebView.reload();
1774 case R.id.add_or_edit_domain:
1775 if (domainSettingsApplied) { // Edit the current domain settings.
1776 // Reapply the domain settings on returning to `MainWebViewActivity`.
1777 reapplyDomainSettingsOnRestart = true;
1778 currentDomainName = "";
1780 // Create an intent to launch the domains activity.
1781 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1783 // Put extra information instructing the domains activity to directly load the current domain and close on back instead of returning to the domains list.
1784 domainsIntent.putExtra("loadDomain", domainSettingsDatabaseId);
1785 domainsIntent.putExtra("closeOnBack", true);
1788 startActivity(domainsIntent);
1789 } else { // Add a new domain.
1790 // Apply the new domain settings on returning to `MainWebViewActivity`.
1791 reapplyDomainSettingsOnRestart = true;
1792 currentDomainName = "";
1794 // Get the current domain
1795 Uri currentUri = Uri.parse(formattedUrlString);
1796 String currentDomain = currentUri.getHost();
1798 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1799 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1801 // Create the domain and store the database ID.
1802 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1804 // Create an intent to launch the domains activity.
1805 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1807 // Put extra information instructing the domains activity to directly load the new domain and close on back instead of returning to the domains list.
1808 domainsIntent.putExtra("loadDomain", newDomainDatabaseId);
1809 domainsIntent.putExtra("closeOnBack", true);
1812 startActivity(domainsIntent);
1816 case R.id.toggle_first_party_cookies:
1817 // Switch the status of firstPartyCookiesEnabled.
1818 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1820 // Update the menu checkbox.
1821 menuItem.setChecked(firstPartyCookiesEnabled);
1823 // Apply the new cookie status.
1824 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1826 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1827 updatePrivacyIcons(true);
1829 // Display a `Snackbar`.
1830 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1831 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1832 } else if (javaScriptEnabled) { // JavaScript is still enabled.
1833 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1834 } else { // Privacy mode.
1835 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1838 // Reload the WebView.
1839 mainWebView.reload();
1842 case R.id.toggle_third_party_cookies:
1843 if (Build.VERSION.SDK_INT >= 21) {
1844 // Switch the status of thirdPartyCookiesEnabled.
1845 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1847 // Update the menu checkbox.
1848 menuItem.setChecked(thirdPartyCookiesEnabled);
1850 // Apply the new cookie status.
1851 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1853 // Display a `Snackbar`.
1854 if (thirdPartyCookiesEnabled) {
1855 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1857 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1860 // Reload the WebView.
1861 mainWebView.reload();
1862 } // Else do nothing because SDK < 21.
1865 case R.id.toggle_dom_storage:
1866 // Switch the status of domStorageEnabled.
1867 domStorageEnabled = !domStorageEnabled;
1869 // Update the menu checkbox.
1870 menuItem.setChecked(domStorageEnabled);
1872 // Apply the new DOM Storage status.
1873 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1875 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1876 updatePrivacyIcons(true);
1878 // Display a `Snackbar`.
1879 if (domStorageEnabled) {
1880 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1882 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1885 // Reload the WebView.
1886 mainWebView.reload();
1889 case R.id.toggle_save_form_data:
1890 // Switch the status of saveFormDataEnabled.
1891 saveFormDataEnabled = !saveFormDataEnabled;
1893 // Update the menu checkbox.
1894 menuItem.setChecked(saveFormDataEnabled);
1896 // Apply the new form data status.
1897 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1899 // Display a `Snackbar`.
1900 if (saveFormDataEnabled) {
1901 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1903 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1906 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1907 updatePrivacyIcons(true);
1909 // Reload the WebView.
1910 mainWebView.reload();
1913 case R.id.clear_cookies:
1914 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1915 .setAction(R.string.undo, v -> {
1916 // Do nothing because everything will be handled by `onDismissed()` below.
1918 .addCallback(new Snackbar.Callback() {
1920 public void onDismissed(Snackbar snackbar, int event) {
1922 // The user pushed the `Undo` button.
1923 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1927 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1929 // `cookieManager.removeAllCookie()` varies by SDK.
1930 if (Build.VERSION.SDK_INT < 21) {
1931 cookieManager.removeAllCookie();
1933 // `null` indicates no callback.
1934 cookieManager.removeAllCookies(null);
1942 case R.id.clear_dom_storage:
1943 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1944 .setAction(R.string.undo, v -> {
1945 // Do nothing because everything will be handled by `onDismissed()` below.
1947 .addCallback(new Snackbar.Callback() {
1949 public void onDismissed(Snackbar snackbar, int event) {
1951 // The user pushed the `Undo` button.
1952 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1956 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1958 // Delete the DOM Storage.
1959 WebStorage webStorage = WebStorage.getInstance();
1960 webStorage.deleteAllData();
1962 // Manually delete the DOM storage files and directories.
1964 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1965 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1967 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1968 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1969 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1970 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1971 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1972 } catch (IOException e) {
1973 // Do nothing if an error is thrown.
1981 case R.id.clear_form_data:
1982 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1983 .setAction(R.string.undo, v -> {
1984 // Do nothing because everything will be handled by `onDismissed()` below.
1986 .addCallback(new Snackbar.Callback() {
1988 public void onDismissed(Snackbar snackbar, int event) {
1990 // The user pushed the `Undo` button.
1991 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1995 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1997 // Delete the form data.
1998 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1999 mainWebViewDatabase.clearFormData();
2006 case R.id.font_size_twenty_five_percent:
2007 mainWebView.getSettings().setTextZoom(25);
2010 case R.id.font_size_fifty_percent:
2011 mainWebView.getSettings().setTextZoom(50);
2014 case R.id.font_size_seventy_five_percent:
2015 mainWebView.getSettings().setTextZoom(75);
2018 case R.id.font_size_one_hundred_percent:
2019 mainWebView.getSettings().setTextZoom(100);
2022 case R.id.font_size_one_hundred_twenty_five_percent:
2023 mainWebView.getSettings().setTextZoom(125);
2026 case R.id.font_size_one_hundred_fifty_percent:
2027 mainWebView.getSettings().setTextZoom(150);
2030 case R.id.font_size_one_hundred_seventy_five_percent:
2031 mainWebView.getSettings().setTextZoom(175);
2034 case R.id.font_size_two_hundred_percent:
2035 mainWebView.getSettings().setTextZoom(200);
2038 case R.id.swipe_to_refresh:
2039 // Toggle swipe to refresh.
2040 swipeRefreshLayout.setEnabled(!swipeRefreshLayout.isEnabled());
2043 case R.id.display_images:
2044 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2045 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2046 mainWebView.reload();
2047 } else { // Images are not currently loaded automatically.
2048 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2051 // Set `onTheFlyDisplayImagesSet`.
2052 onTheFlyDisplayImagesSet = true;
2055 case R.id.view_source:
2056 // Launch the View Source activity.
2057 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2058 startActivity(viewSourceIntent);
2062 // Setup the share string.
2063 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2065 // Create the share intent.
2066 Intent shareIntent = new Intent();
2067 shareIntent.setAction(Intent.ACTION_SEND);
2068 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2069 shareIntent.setType("text/plain");
2072 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2075 case R.id.find_on_page:
2076 // Hide the URL app bar.
2077 supportAppBar.setVisibility(View.GONE);
2079 // Show the Find on Page `RelativeLayout`.
2080 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2082 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2083 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2084 findOnPageEditText.postDelayed(() -> {
2085 // Set the focus on `findOnPageEditText`.
2086 findOnPageEditText.requestFocus();
2088 // Display the keyboard. `0` sets no input flags.
2089 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2094 // Get a `PrintManager` instance.
2095 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2097 // Convert `mainWebView` to `printDocumentAdapter`.
2098 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2100 // Remove the lint error below that `printManager` might be `null`.
2101 assert printManager != null;
2103 // Print the document. The print attributes are `null`.
2104 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2107 case R.id.add_to_homescreen:
2108 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2109 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2110 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2112 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2116 mainWebView.reload();
2119 case R.id.ad_consent:
2120 // Display the ad consent dialog.
2121 DialogFragment adConsentDialogFragment = new AdConsentDialog();
2122 adConsentDialogFragment.show(getFragmentManager(), getString(R.string.ad_consent));
2126 // Don't consume the event.
2127 return super.onOptionsItemSelected(menuItem);
2131 // removeAllCookies is deprecated, but it is required for API < 21.
2132 @SuppressWarnings("deprecation")
2134 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2135 int menuItemId = menuItem.getItemId();
2137 switch (menuItemId) {
2143 if (mainWebView.canGoBack()) {
2144 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2145 navigatingHistory = true;
2147 // Load the previous website in the history.
2148 mainWebView.goBack();
2153 if (mainWebView.canGoForward()) {
2154 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2155 navigatingHistory = true;
2157 // Load the next website in the history.
2158 mainWebView.goForward();
2163 // Get the `WebBackForwardList`.
2164 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2166 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2167 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2168 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2171 case R.id.downloads:
2172 // Launch the system Download Manager.
2173 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2175 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2176 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2178 startActivity(downloadManagerIntent);
2182 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2183 reapplyDomainSettingsOnRestart = true;
2184 currentDomainName = "";
2186 // Launch `DomainsActivity`.
2187 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2188 startActivity(domainsIntent);
2192 // Set the flag to reapply app settings on restart when returning from Settings.
2193 reapplyAppSettingsOnRestart = true;
2195 // Set the flag to reapply the domain settings on restart when returning from Settings.
2196 reapplyDomainSettingsOnRestart = true;
2197 currentDomainName = "";
2199 // Launch `SettingsActivity`.
2200 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2201 startActivity(settingsIntent);
2205 // Launch `GuideActivity`.
2206 Intent guideIntent = new Intent(this, GuideActivity.class);
2207 startActivity(guideIntent);
2211 // Launch `AboutActivity`.
2212 Intent aboutIntent = new Intent(this, AboutActivity.class);
2213 startActivity(aboutIntent);
2216 case R.id.clearAndExit:
2217 // Get a handle for `sharedPreferences`. `this` references the current context.
2218 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2220 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2223 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2224 // The command to remove cookies changed slightly in API 21.
2225 if (Build.VERSION.SDK_INT >= 21) {
2226 cookieManager.removeAllCookies(null);
2228 cookieManager.removeAllCookie();
2231 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2233 // We have to use two commands because `Runtime.exec()` does not like `*`.
2234 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2235 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2236 } catch (IOException e) {
2237 // Do nothing if an error is thrown.
2241 // Clear DOM storage.
2242 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2243 // Ask `WebStorage` to clear the DOM storage.
2244 WebStorage webStorage = WebStorage.getInstance();
2245 webStorage.deleteAllData();
2247 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2249 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2250 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2252 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2253 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2254 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2255 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2256 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2257 } catch (IOException e) {
2258 // Do nothing if an error is thrown.
2263 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2264 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2265 webViewDatabase.clearFormData();
2267 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2269 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2270 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2271 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2272 } catch (IOException e) {
2273 // Do nothing if an error is thrown.
2278 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2279 // `true` includes disk files.
2280 mainWebView.clearCache(true);
2282 // Manually delete the cache directories.
2284 // Delete the main cache directory.
2285 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2287 // Delete the secondary `Service Worker` cache directory.
2288 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2289 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2290 } catch (IOException e) {
2291 // Do nothing if an error is thrown.
2295 // Clear SSL certificate preferences.
2296 mainWebView.clearSslPreferences();
2298 // Clear the back/forward history.
2299 mainWebView.clearHistory();
2301 // Clear `formattedUrlString`.
2302 formattedUrlString = null;
2304 // Clear `customHeaders`.
2305 customHeaders.clear();
2307 // Detach all views from `mainWebViewRelativeLayout`.
2308 mainWebViewRelativeLayout.removeAllViews();
2310 // Destroy the internal state of `mainWebView`.
2311 mainWebView.destroy();
2313 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2314 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2315 if (clearEverything) {
2317 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2318 } catch (IOException e) {
2319 // Do nothing if an error is thrown.
2323 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2324 if (Build.VERSION.SDK_INT >= 21) {
2325 finishAndRemoveTask();
2330 // Remove the terminated program from RAM. The status code is `0`.
2335 // Close the navigation drawer.
2336 drawerLayout.closeDrawer(GravityCompat.START);
2341 public void onPostCreate(Bundle savedInstanceState) {
2342 super.onPostCreate(savedInstanceState);
2344 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2345 drawerToggle.syncState();
2349 public void onConfigurationChanged(Configuration newConfig) {
2350 super.onConfigurationChanged(newConfig);
2352 // Reload the ad for the free flavor if we are not in full screen mode.
2353 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2354 // Reload the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
2355 AdHelper.loadAd(findViewById(R.id.adview), getApplicationContext(), getString(R.string.ad_id));
2358 // `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:
2359 // https://code.google.com/p/android/issues/detail?id=20493#c8
2360 // ActivityCompat.invalidateOptionsMenu(this);
2364 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2365 // Store the `HitTestResult`.
2366 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2369 final String imageUrl;
2370 final String linkUrl;
2372 // Get a handle for the `ClipboardManager`.
2373 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2375 // Remove the lint errors below that `clipboardManager` might be `null`.
2376 assert clipboardManager != null;
2378 switch (hitTestResult.getType()) {
2379 // `SRC_ANCHOR_TYPE` is a link.
2380 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2381 // Get the target URL.
2382 linkUrl = hitTestResult.getExtra();
2384 // Set the target URL as the title of the `ContextMenu`.
2385 menu.setHeaderTitle(linkUrl);
2387 // Add a Load URL entry.
2388 menu.add(R.string.load_url).setOnMenuItemClickListener((MenuItem item) -> {
2393 // Add a Copy URL entry.
2394 menu.add(R.string.copy_url).setOnMenuItemClickListener((MenuItem item) -> {
2395 // Save the link URL in a `ClipData`.
2396 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2398 // Set the `ClipData` as the clipboard's primary clip.
2399 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2403 // Add a Download URL entry.
2404 menu.add(R.string.download_url).setOnMenuItemClickListener((MenuItem item) -> {
2405 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2406 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2407 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2409 // Store the variables for future use by `onRequestPermissionsResult()`.
2410 downloadUrl = linkUrl;
2411 downloadContentDisposition = "none";
2412 downloadContentLength = -1;
2414 // Show a dialog if the user has previously denied the permission.
2415 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2416 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
2417 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
2419 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
2420 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2421 } else { // Show the permission request directly.
2422 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
2423 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2425 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2426 // Get a handle for the download file alert dialog.
2427 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(linkUrl, "none", -1);
2429 // Show the download file alert dialog.
2430 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2435 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2436 menu.add(R.string.cancel);
2439 case WebView.HitTestResult.EMAIL_TYPE:
2440 // Get the target URL.
2441 linkUrl = hitTestResult.getExtra();
2443 // Set the target URL as the title of the `ContextMenu`.
2444 menu.setHeaderTitle(linkUrl);
2446 // Add a `Write Email` entry.
2447 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2448 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2449 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2451 // Parse the url and set it as the data for the `Intent`.
2452 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2454 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2455 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2458 startActivity(emailIntent);
2462 // Add a `Copy Email Address` entry.
2463 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2464 // Save the email address in a `ClipData`.
2465 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2467 // Set the `ClipData` as the clipboard's primary clip.
2468 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2472 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2473 menu.add(R.string.cancel);
2476 // `IMAGE_TYPE` is an image.
2477 case WebView.HitTestResult.IMAGE_TYPE:
2478 // Get the image URL.
2479 imageUrl = hitTestResult.getExtra();
2481 // Set the image URL as the title of the `ContextMenu`.
2482 menu.setHeaderTitle(imageUrl);
2484 // Add a `View Image` entry.
2485 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2490 // Add a `Download Image` entry.
2491 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2492 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2493 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2494 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2496 // Store the image URL for use by `onRequestPermissionResult()`.
2497 downloadImageUrl = imageUrl;
2499 // Show a dialog if the user has previously denied the permission.
2500 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2501 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2502 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2504 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2505 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2506 } else { // Show the permission request directly.
2507 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2508 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2510 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2511 // Get a handle for the download image alert dialog.
2512 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2514 // Show the download image alert dialog.
2515 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2520 // Add a `Copy URL` entry.
2521 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2522 // Save the image URL in a `ClipData`.
2523 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2525 // Set the `ClipData` as the clipboard's primary clip.
2526 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2530 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2531 menu.add(R.string.cancel);
2535 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2536 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2537 // Get the image URL.
2538 imageUrl = hitTestResult.getExtra();
2540 // Set the image URL as the title of the `ContextMenu`.
2541 menu.setHeaderTitle(imageUrl);
2543 // Add a `View Image` entry.
2544 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2549 // Add a `Download Image` entry.
2550 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2551 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2552 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2553 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2555 // Store the image URL for use by `onRequestPermissionResult()`.
2556 downloadImageUrl = imageUrl;
2558 // Show a dialog if the user has previously denied the permission.
2559 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2560 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2561 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2563 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2564 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2565 } else { // Show the permission request directly.
2566 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2567 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2569 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2570 // Get a handle for the download image alert dialog.
2571 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2573 // Show the download image alert dialog.
2574 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2579 // Add a `Copy URL` entry.
2580 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2581 // Save the image URL in a `ClipData`.
2582 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2584 // Set the `ClipData` as the clipboard's primary clip.
2585 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2589 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2590 menu.add(R.string.cancel);
2596 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2597 // Get the `EditTexts` from the `dialogFragment`.
2598 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2599 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2601 // Extract the strings from the `EditTexts`.
2602 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2603 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2605 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2606 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2607 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2608 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2610 // Display the new bookmark below the current items in the (0 indexed) list.
2611 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2613 // Create the bookmark.
2614 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2616 // Update `bookmarksCursor` with the current contents of this folder.
2617 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2619 // Update the `ListView`.
2620 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2622 // Scroll to the new bookmark.
2623 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2627 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2628 // Get handles for the views in `dialogFragment`.
2629 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2630 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2631 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2633 // Get new folder name string.
2634 String folderNameString = createFolderNameEditText.getText().toString();
2636 // Get the new folder icon `Bitmap`.
2637 Bitmap folderIconBitmap;
2638 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2639 // Get the default folder icon and convert it to a `Bitmap`.
2640 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2641 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2642 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2643 } else { // Use the `WebView` favorite icon.
2644 folderIconBitmap = favoriteIconBitmap;
2647 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2648 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2649 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2650 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2652 // Move all the bookmarks down one in the display order.
2653 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2654 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2655 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2658 // Create the folder, which will be placed at the top of the `ListView`.
2659 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2661 // Update `bookmarksCursor` with the current contents of this folder.
2662 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2664 // Update the `ListView`.
2665 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2667 // Scroll to the new folder.
2668 bookmarksListView.setSelection(0);
2672 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2673 // Get the shortcut name.
2674 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2675 String shortcutNameString = shortcutNameEditText.getText().toString();
2677 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2678 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2680 // Setup the shortcut intent.
2681 Intent shortcutIntent = new Intent();
2682 shortcutIntent.setAction(Intent.ACTION_VIEW);
2683 shortcutIntent.setData(Uri.parse(formattedUrlString));
2685 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2686 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2688 // Add the required fields to the shortcut info builder.
2689 shortcutInfoBuilder.setIcon(favoriteIcon);
2690 shortcutInfoBuilder.setIntent(shortcutIntent);
2691 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2693 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2694 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2698 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2699 switch (downloadType) {
2700 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2701 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2702 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2705 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2706 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2707 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2713 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
2714 switch (requestCode) {
2715 case DOWNLOAD_FILE_REQUEST_CODE:
2716 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2717 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2719 // On API 23, displaying the fragment must be delayed or the app will crash.
2720 if (Build.VERSION.SDK_INT == 23) {
2721 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2723 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2726 // Reset the download variables.
2728 downloadContentDisposition = "";
2729 downloadContentLength = 0;
2732 case DOWNLOAD_IMAGE_REQUEST_CODE:
2733 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2734 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2736 // On API 23, displaying the fragment must be delayed or the app will crash.
2737 if (Build.VERSION.SDK_INT == 23) {
2738 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2740 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2743 // Reset the image URL variable.
2744 downloadImageUrl = "";
2750 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2751 // Download the image if it has an HTTP or HTTPS URI.
2752 if (imageUrl.startsWith("http")) {
2753 // Get a handle for the system `DOWNLOAD_SERVICE`.
2754 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2756 // Parse `imageUrl`.
2757 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2759 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2760 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2761 if (firstPartyCookiesEnabled) {
2762 // Get the cookies for `imageUrl`.
2763 String cookies = cookieManager.getCookie(imageUrl);
2765 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2766 downloadRequest.addRequestHeader("Cookie", cookies);
2769 // Get the file name from the dialog fragment.
2770 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2771 String imageName = downloadImageNameEditText.getText().toString();
2773 // Specify the download location.
2774 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2775 // Download to the public download directory.
2776 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2777 } else { // External write permission denied.
2778 // Download to the app's external download directory.
2779 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2782 // Allow `MediaScanner` to index the download if it is a media file.
2783 downloadRequest.allowScanningByMediaScanner();
2785 // Add the URL as the description for the download.
2786 downloadRequest.setDescription(imageUrl);
2788 // Show the download notification after the download is completed.
2789 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2791 // Remove the lint warning below that `downloadManager` might be `null`.
2792 assert downloadManager != null;
2794 // Initiate the download.
2795 downloadManager.enqueue(downloadRequest);
2796 } else { // The image is not an HTTP or HTTPS URI.
2797 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2802 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2803 // Download the file if it has an HTTP or HTTPS URI.
2804 if (downloadUrl.startsWith("http")) {
2805 // Get a handle for the system `DOWNLOAD_SERVICE`.
2806 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2808 // Parse `downloadUrl`.
2809 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2811 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2812 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2813 if (firstPartyCookiesEnabled) {
2814 // Get the cookies for `downloadUrl`.
2815 String cookies = cookieManager.getCookie(downloadUrl);
2817 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2818 downloadRequest.addRequestHeader("Cookie", cookies);
2821 // Get the file name from the dialog fragment.
2822 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2823 String fileName = downloadFileNameEditText.getText().toString();
2825 // Specify the download location.
2826 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2827 // Download to the public download directory.
2828 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2829 } else { // External write permission denied.
2830 // Download to the app's external download directory.
2831 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2834 // Allow `MediaScanner` to index the download if it is a media file.
2835 downloadRequest.allowScanningByMediaScanner();
2837 // Add the URL as the description for the download.
2838 downloadRequest.setDescription(downloadUrl);
2840 // Show the download notification after the download is completed.
2841 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2843 // Remove the lint warning below that `downloadManager` might be `null`.
2844 assert downloadManager != null;
2846 // Initiate the download.
2847 downloadManager.enqueue(downloadRequest);
2848 } else { // The download is not an HTTP or HTTPS URI.
2849 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2854 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2855 // Get handles for the views from `dialogFragment`.
2856 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2857 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2858 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2860 // Store the bookmark strings.
2861 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2862 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2864 // Update the bookmark.
2865 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2866 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2867 } else { // Update the bookmark using the `WebView` favorite icon.
2868 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2869 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2870 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2871 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2873 // Update the bookmark and the favorite icon.
2874 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2877 // Update `bookmarksCursor` with the current contents of this folder.
2878 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2880 // Update the `ListView`.
2881 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2885 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2886 // Get handles for the views from `dialogFragment`.
2887 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2888 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2889 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2890 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2892 // Get the new folder name.
2893 String newFolderNameString = editFolderNameEditText.getText().toString();
2895 // Check if the favorite icon has changed.
2896 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2897 // Update the name in the database.
2898 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2899 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2900 // Get the new folder icon `Bitmap`.
2901 Bitmap folderIconBitmap;
2902 if (defaultFolderIconRadioButton.isChecked()) {
2903 // Get the default folder icon and convert it to a `Bitmap`.
2904 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2905 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2906 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2907 } else { // Use the `WebView` favorite icon.
2908 folderIconBitmap = favoriteIconBitmap;
2911 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2912 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2913 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2914 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2916 // Update the folder icon in the database.
2917 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2918 } else { // The folder icon and the name have changed.
2919 // Get the new folder icon `Bitmap`.
2920 Bitmap folderIconBitmap;
2921 if (defaultFolderIconRadioButton.isChecked()) {
2922 // Get the default folder icon and convert it to a `Bitmap`.
2923 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2924 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2925 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2926 } else { // Use the `WebView` favorite icon.
2927 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2930 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2931 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2932 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2933 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2935 // Update the folder name and icon in the database.
2936 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2939 // Update `bookmarksCursor` with the current contents of this folder.
2940 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2942 // Update the `ListView`.
2943 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2947 public void onHttpAuthenticationCancel() {
2948 // Cancel the `HttpAuthHandler`.
2949 httpAuthHandler.cancel();
2953 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2954 // Get handles for the `EditTexts`.
2955 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2956 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2958 // Proceed with the HTTP authentication.
2959 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2962 public void viewSslCertificate(View view) {
2963 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2964 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2965 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2969 public void onSslErrorCancel() {
2970 sslErrorHandler.cancel();
2974 public void onSslErrorProceed() {
2975 sslErrorHandler.proceed();
2979 public void onSslMismatchBack() {
2980 if (mainWebView.canGoBack()) { // There is a back page in the history.
2981 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2982 navigatingHistory = true;
2985 mainWebView.goBack();
2986 } else { // There are no pages to go back to.
2987 // Load a blank page
2993 public void onSslMismatchProceed() {
2994 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2995 ignorePinnedSslCertificate = true;
2999 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3000 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3001 navigatingHistory = true;
3003 // Load the history entry.
3004 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3008 public void onClearHistory() {
3009 // Clear the history.
3010 mainWebView.clearHistory();
3013 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3015 public void onBackPressed() {
3016 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3017 // Close the navigation drawer.
3018 drawerLayout.closeDrawer(GravityCompat.START);
3019 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3020 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3021 // close the bookmarks drawer.
3022 drawerLayout.closeDrawer(GravityCompat.END);
3023 } else { // A subfolder is displayed.
3024 // Place the former parent folder in `currentFolder`.
3025 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3027 // Load the new folder.
3028 loadBookmarksFolder();
3031 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3032 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3033 navigatingHistory = true;
3036 mainWebView.goBack();
3037 } else { // There isn't anything to do in Privacy Browser.
3038 // Pass `onBackPressed()` to the system.
3039 super.onBackPressed();
3043 // 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.
3045 public void onActivityResult(int requestCode, int resultCode, Intent data) {
3046 // File uploads only work on API >= 21.
3047 if (Build.VERSION.SDK_INT >= 21) {
3048 // Pass the file to the WebView.
3049 fileChooserCallback.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
3053 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3054 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3055 String unformattedUrlString = urlTextBox.getText().toString().trim();
3057 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3058 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3059 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3060 if (!unformattedUrlString.startsWith("http")) {
3061 unformattedUrlString = "http://" + unformattedUrlString;
3064 // Initialize `unformattedUrl`.
3065 URL unformattedUrl = null;
3067 // 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.
3069 unformattedUrl = new URL(unformattedUrlString);
3070 } catch (MalformedURLException e) {
3071 e.printStackTrace();
3074 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3075 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3076 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3077 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3078 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3079 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3082 Uri.Builder formattedUri = new Uri.Builder();
3083 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3085 // Decode `formattedUri` as a `String` in `UTF-8`.
3086 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3088 // Sanitize the search input and convert it to a search.
3089 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3091 // Add the base search URL.
3092 formattedUrlString = searchURL + encodedUrlString;
3095 // 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.
3096 urlTextBox.clearFocus();
3098 loadUrl(formattedUrlString);
3102 private void loadUrl(String url) {
3103 // Apply any custom domain settings.
3104 applyDomainSettings(url, true, false);
3107 mainWebView.loadUrl(url, customHeaders);
3109 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3110 urlIsLoading = true;
3113 public void findPreviousOnPage(View view) {
3114 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3115 mainWebView.findNext(false);
3118 public void findNextOnPage(View view) {
3119 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3120 mainWebView.findNext(true);
3123 public void closeFindOnPage(View view) {
3124 // Delete the contents of `find_on_page_edittext`.
3125 findOnPageEditText.setText(null);
3127 // Clear the highlighted phrases.
3128 mainWebView.clearMatches();
3130 // Hide the Find on Page `RelativeLayout`.
3131 findOnPageLinearLayout.setVisibility(View.GONE);
3133 // Show the URL app bar.
3134 supportAppBar.setVisibility(View.VISIBLE);
3136 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3137 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3140 private void applyAppSettings() {
3141 // Get a handle for the shared preferences.
3142 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3144 // Store the values from the shared preferences in variables.
3145 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3146 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3147 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3148 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3149 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3150 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3151 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3152 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3153 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3154 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3155 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3156 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3157 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3159 // Set the homepage, search, and proxy options.
3160 if (proxyThroughOrbot) { // Set the Tor options.
3161 // Set `torHomepageString` as `homepage`.
3162 homepage = torHomepageString;
3164 // If formattedUrlString is null assign the homepage to it.
3165 if (formattedUrlString == null) {
3166 formattedUrlString = homepage;
3169 // Set the search URL.
3170 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3171 searchURL = torSearchCustomURLString;
3172 } else { // Use the string from the pre-built list.
3173 searchURL = torSearchString;
3176 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3177 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3179 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3181 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3183 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3186 // Display a message to the user if we are waiting on Orbot.
3187 if (!orbotStatus.equals("ON")) {
3188 // Set `waitingForOrbot`.
3189 waitingForOrbot = true;
3191 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3192 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3194 } else { // Set the non-Tor options.
3195 // Set `homepageString` as `homepage`.
3196 homepage = homepageString;
3198 // If formattedUrlString is null assign the homepage to it.
3199 if (formattedUrlString == null) {
3200 formattedUrlString = homepage;
3203 // Set the search URL.
3204 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3205 searchURL = searchCustomURLString;
3206 } else { // Use the string from the pre-built list.
3207 searchURL = searchString;
3210 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3211 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3213 // Set the default `appBar` background. `this` refers to the context.
3215 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3217 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3220 // Reset `waitingForOrbot.
3221 waitingForOrbot = false;
3224 // Set Do Not Track status.
3225 if (doNotTrackEnabled) {
3226 customHeaders.put("DNT", "1");
3228 customHeaders.remove("DNT");
3231 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3232 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3233 if (hideSystemBarsOnFullscreen) { // Hide everything.
3234 // Remove the translucent navigation setting if it is currently flagged.
3235 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3237 // Remove the translucent status bar overlay.
3238 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3240 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3241 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3243 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3244 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3245 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3247 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3248 } else { // Hide everything except the status and navigation bars.
3249 // Add the translucent status flag if it is unset.
3250 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3252 if (translucentNavigationBarOnFullscreen) {
3253 // Set the navigation bar to be translucent.
3254 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3256 // Set the navigation bar to be black.
3257 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3260 } else { // Switch to normal viewing mode.
3261 // Reset `inFullScreenBrowsingMode` to `false`.
3262 inFullScreenBrowsingMode = false;
3264 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3265 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3269 // Show the `BannerAd` in the free flavor.
3270 if (BuildConfig.FLAVOR.contentEquals("free")) {
3271 // Initialize the ad. The AdView is destroyed and recreated, which changes the ID, every time it is reloaded to handle possible rotations.
3272 AdHelper.initializeAds(findViewById(R.id.adview), getApplicationContext(), getFragmentManager(), getString(R.string.ad_id));
3275 // Remove the translucent navigation bar flag if it is set.
3276 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3278 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3279 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3281 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3282 rootCoordinatorLayout.setSystemUiVisibility(0);
3284 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3285 rootCoordinatorLayout.setFitsSystemWindows(true);
3289 // `reloadWebsite` is used if returning from the Domains activity. Otherwise JavaScript might not function correctly if it is newly enabled.
3290 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3291 @SuppressWarnings("deprecation")
3292 private void applyDomainSettings(String url, boolean resetFavoriteIcon, boolean reloadWebsite) {
3293 // Reset `navigatingHistory`.
3294 navigatingHistory = false;
3296 // Parse the URL into a URI.
3297 Uri uri = Uri.parse(url);
3299 // Extract the domain from `uri`.
3300 String hostName = uri.getHost();
3302 // Initialize `loadingNewDomainName`.
3303 boolean loadingNewDomainName;
3305 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3306 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3307 //noinspection SimplifiableIfStatement
3308 if ((hostName == null) || (currentDomainName == null)) {
3309 loadingNewDomainName = true;
3310 } else { // Determine if `hostName` equals `currentDomainName`.
3311 loadingNewDomainName = !hostName.equals(currentDomainName);
3314 // 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.
3315 if (loadingNewDomainName) {
3316 // Set the new `hostname` as the `currentDomainName`.
3317 currentDomainName = hostName;
3319 // Reset `ignorePinnedSslCertificate`.
3320 ignorePinnedSslCertificate = false;
3322 // Reset the favorite icon if specified.
3323 if (resetFavoriteIcon) {
3324 favoriteIconBitmap = favoriteIconDefaultBitmap;
3325 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3328 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3329 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3330 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3332 // Get a full cursor from `domainsDatabaseHelper`.
3333 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3335 // Initialize `domainSettingsSet`.
3336 Set<String> domainSettingsSet = new HashSet<>();
3338 // Get the domain name column index.
3339 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3341 // Populate `domainSettingsSet`.
3342 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3343 // Move `domainsCursor` to the current row.
3344 domainNameCursor.moveToPosition(i);
3346 // Store the domain name in `domainSettingsSet`.
3347 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3350 // Close `domainNameCursor.
3351 domainNameCursor.close();
3353 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3354 domainSettingsApplied = false;
3355 String domainNameInDatabase = null;
3357 // Check the hostname.
3358 if (domainSettingsSet.contains(hostName)) {
3359 domainSettingsApplied = true;
3360 domainNameInDatabase = hostName;
3363 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3364 if (hostName != null) {
3365 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3366 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3367 domainSettingsApplied = true;
3368 domainNameInDatabase = "*." + hostName;
3371 // Strip out the lowest subdomain of `host`.
3372 hostName = hostName.substring(hostName.indexOf(".") + 1);
3376 // Get a handle for the shared preference. `this` references the current context.
3377 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3379 // Store the general preference information.
3380 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3381 String defaultUserAgentName = sharedPreferences.getString("user_agent", "Privacy Browser");
3382 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3383 boolean defaultSwipeToRefresh = sharedPreferences.getBoolean("swipe_to_refresh", true);
3384 nightMode = sharedPreferences.getBoolean("night_mode", false);
3386 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3387 // Get a cursor for the current host and move it to the first position.
3388 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3389 currentHostDomainSettingsCursor.moveToFirst();
3391 // Get the settings from the cursor.
3392 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3393 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3394 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3395 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3396 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3397 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3398 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3399 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3400 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3401 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3402 String userAgentName = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3403 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3404 int swipeToRefreshInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SWIPE_TO_REFRESH));
3405 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3406 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3407 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3408 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3409 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3410 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3411 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3412 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3413 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3415 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3416 switch (nightModeInt) {
3417 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3421 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3426 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3428 javaScriptEnabled = true;
3431 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3432 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3433 pinnedDomainSslStartDate = null;
3435 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3438 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3439 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3440 pinnedDomainSslEndDate = null;
3442 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3445 // Close `currentHostDomainSettingsCursor`.
3446 currentHostDomainSettingsCursor.close();
3448 // Apply the domain settings.
3449 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3450 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3451 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3452 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3454 // Apply the font size.
3455 if (fontSize == 0) { // Apply the default font size.
3456 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3457 } else { // Apply the specified font size.
3458 mainWebView.getSettings().setTextZoom(fontSize);
3461 // Set third-party cookies status if API >= 21.
3462 if (Build.VERSION.SDK_INT >= 21) {
3463 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3466 // 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.
3467 // <https://redmine.stoutner.com/issues/160>
3468 if (!urlIsLoading) {
3469 // Set the user agent.
3470 if (userAgentName.equals(getString(R.string.system_default_user_agent))) { // Use the system default user agent.
3471 // Get the array position of the default user agent name.
3472 int defaultUserAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3474 // Set the user agent according to the system default.
3475 switch (defaultUserAgentArrayPosition) {
3476 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3477 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3478 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3481 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3482 // Set the user agent to `""`, which uses the default value.
3483 mainWebView.getSettings().setUserAgentString("");
3486 case SETTINGS_CUSTOM_USER_AGENT:
3487 // Set the custom user agent.
3488 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3492 // Get the user agent string from the user agent data array
3493 mainWebView.getSettings().setUserAgentString(userAgentDataArray[defaultUserAgentArrayPosition]);
3495 } else { // Set the user agent according to the stored name.
3496 // Get the array position of the user agent name.
3497 int userAgentArrayPosition = userAgentNamesArray.getPosition(userAgentName);
3499 switch (userAgentArrayPosition) {
3500 case UNRECOGNIZED_USER_AGENT: // The user agent name contains a custom user agent.
3501 mainWebView.getSettings().setUserAgentString(userAgentName);
3504 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3505 // Set the user agent to `""`, which uses the default value.
3506 mainWebView.getSettings().setUserAgentString("");
3510 // Get the user agent string from the user agent data array.
3511 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3515 // Set swipe to refresh.
3516 switch (swipeToRefreshInt) {
3517 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_SYSTEM_DEFAULT:
3518 // Set swipe to refresh according to the default.
3519 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3522 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_ENABLED:
3523 // Enable swipe to refresh.
3524 swipeRefreshLayout.setEnabled(true);
3527 case DomainsDatabaseHelper.SWIPE_TO_REFRESH_DISABLED:
3528 // Disable swipe to refresh.
3529 swipeRefreshLayout.setEnabled(false);
3532 // Store the applied user agent string, which is used in the View Source activity.
3533 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3536 // 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.
3538 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3540 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3542 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3543 // Store the values from `sharedPreferences` in variables.
3544 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3545 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3546 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3547 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3548 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3549 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3550 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3551 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3552 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3554 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3556 javaScriptEnabled = true;
3559 // Apply the default settings.
3560 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3561 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3562 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3563 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3564 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3565 swipeRefreshLayout.setEnabled(defaultSwipeToRefresh);
3567 // Reset the pinned SSL certificate information.
3568 domainSettingsDatabaseId = -1;
3569 pinnedDomainSslCertificate = false;
3570 pinnedDomainSslIssuedToCNameString = "";
3571 pinnedDomainSslIssuedToONameString = "";
3572 pinnedDomainSslIssuedToUNameString = "";
3573 pinnedDomainSslIssuedByCNameString = "";
3574 pinnedDomainSslIssuedByONameString = "";
3575 pinnedDomainSslIssuedByUNameString = "";
3576 pinnedDomainSslStartDate = null;
3577 pinnedDomainSslEndDate = null;
3579 // Set third-party cookies status if API >= 21.
3580 if (Build.VERSION.SDK_INT >= 21) {
3581 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3584 // 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.
3585 // <https://redmine.stoutner.com/issues/160>
3586 if (!urlIsLoading) {
3587 // Get the array position of the user agent name.
3588 int userAgentArrayPosition = userAgentNamesArray.getPosition(defaultUserAgentName);
3590 // Set the user agent.
3591 switch (userAgentArrayPosition) {
3592 case UNRECOGNIZED_USER_AGENT: // The default user agent name is not on the canonical list.
3593 // This is probably because it was set in an older version of Privacy Browser before the switch to persistent user agent names.
3594 mainWebView.getSettings().setUserAgentString(defaultUserAgentName);
3597 case SETTINGS_WEBVIEW_DEFAULT_USER_AGENT:
3598 // Set the user agent to `""`, which uses the default value.
3599 mainWebView.getSettings().setUserAgentString("");
3602 case SETTINGS_CUSTOM_USER_AGENT:
3603 // Set the custom user agent.
3604 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3608 // Get the user agent string from the user agent data array
3609 mainWebView.getSettings().setUserAgentString(userAgentDataArray[userAgentArrayPosition]);
3612 // Store the applied user agent string, which is used in the View Source activity.
3613 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3616 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3617 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3620 // Close `domainsDatabaseHelper`.
3621 domainsDatabaseHelper.close();
3623 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3624 onTheFlyDisplayImagesSet = false;
3625 setDisplayWebpageImages();
3627 // Update the privacy icons, but only if `mainMenu` has already been populated.
3628 if (mainMenu != null) {
3629 updatePrivacyIcons(true);
3632 // Reload the website if returning from the Domains activity.
3633 if (reloadWebsite) {
3634 mainWebView.reload();
3639 private void setDisplayWebpageImages() {
3640 if (!onTheFlyDisplayImagesSet) {
3641 if (domainSettingsApplied) { // Custom domain settings are applied.
3642 switch (displayWebpageImagesInt) {
3643 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3644 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3647 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3648 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3651 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3652 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3655 } else { // Default settings are applied.
3656 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3661 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3662 // Get handles for the menu items.
3663 MenuItem privacyMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3664 MenuItem firstPartyCookiesMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3665 MenuItem domStorageMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3666 MenuItem refreshMenuItem = mainMenu.findItem(R.id.refresh);
3668 // Update the privacy icon.
3669 if (javaScriptEnabled) { // JavaScript is enabled.
3670 privacyMenuItem.setIcon(R.drawable.javascript_enabled);
3671 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3672 privacyMenuItem.setIcon(R.drawable.warning);
3673 } else { // All the dangerous features are disabled.
3674 privacyMenuItem.setIcon(R.drawable.privacy_mode);
3677 // Update the first-party cookies icon.
3678 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3679 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_enabled);
3680 } else { // First-party cookies are disabled.
3682 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3684 firstPartyCookiesMenuItem.setIcon(R.drawable.cookies_disabled_light);
3688 // Update the DOM storage icon.
3689 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3690 domStorageMenuItem.setIcon(R.drawable.dom_storage_enabled);
3691 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3693 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3695 domStorageMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3697 } else { // JavaScript is disabled, so DOM storage is ghosted.
3699 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3701 domStorageMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3705 // Update the refresh icon.
3707 refreshMenuItem.setIcon(R.drawable.refresh_enabled_dark);
3709 refreshMenuItem.setIcon(R.drawable.refresh_enabled_light);
3712 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3713 if (runInvalidateOptionsMenu) {
3714 invalidateOptionsMenu();
3718 private void highlightUrlText() {
3719 String urlString = urlTextBox.getText().toString();
3721 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3722 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3723 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3724 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3727 // Get the index of the `/` immediately after the domain name.
3728 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3730 // De-emphasize the text after the domain name.
3731 if (endOfDomainName > 0) {
3732 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3736 private void loadBookmarksFolder() {
3737 // Update the bookmarks cursor with the contents of the bookmarks database for the current folder.
3738 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3740 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3741 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3743 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3744 // Inflate the individual item layout. `false` does not attach it to the root.
3745 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3749 public void bindView(View view, Context context, Cursor cursor) {
3750 // Get handles for the views.
3751 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3752 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3754 // Get the favorite icon byte array from the cursor.
3755 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3757 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3758 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3760 // Display the bitmap in `bookmarkFavoriteIcon`.
3761 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3763 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3764 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3765 bookmarkNameTextView.setText(bookmarkNameString);
3767 // Make the font bold for folders.
3768 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3769 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3770 } else { // Reset the font to default for normal bookmarks.
3771 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3776 // Populate the `ListView` with the adapter.
3777 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3779 // Set the bookmarks drawer title.
3780 if (currentBookmarksFolder.isEmpty()) {
3781 bookmarksTitleTextView.setText(R.string.bookmarks);
3783 bookmarksTitleTextView.setText(currentBookmarksFolder);