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.WebBackForwardList;
92 import android.webkit.WebChromeClient;
93 import android.webkit.WebResourceResponse;
94 import android.webkit.WebStorage;
95 import android.webkit.WebView;
96 import android.webkit.WebViewClient;
97 import android.webkit.WebViewDatabase;
98 import android.widget.CursorAdapter;
99 import android.widget.EditText;
100 import android.widget.FrameLayout;
101 import android.widget.ImageView;
102 import android.widget.LinearLayout;
103 import android.widget.ListView;
104 import android.widget.ProgressBar;
105 import android.widget.RadioButton;
106 import android.widget.RelativeLayout;
107 import android.widget.TextView;
109 import com.stoutner.privacybrowser.BannerAd;
110 import com.stoutner.privacybrowser.BuildConfig;
111 import com.stoutner.privacybrowser.R;
112 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
113 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
114 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
115 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
116 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
117 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
118 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
119 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
120 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
121 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
122 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
123 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
124 import com.stoutner.privacybrowser.helpers.BlockListHelper;
125 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
126 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
127 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
128 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
129 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
131 import java.io.ByteArrayInputStream;
132 import java.io.ByteArrayOutputStream;
134 import java.io.IOException;
135 import java.io.UnsupportedEncodingException;
136 import java.net.MalformedURLException;
138 import java.net.URLDecoder;
139 import java.net.URLEncoder;
140 import java.util.ArrayList;
141 import java.util.Date;
142 import java.util.HashMap;
143 import java.util.HashSet;
144 import java.util.List;
145 import java.util.Map;
146 import java.util.Set;
148 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
149 public class MainWebViewActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener, CreateBookmarkDialog.CreateBookmarkListener,
150 CreateBookmarkFolderDialog.CreateBookmarkFolderListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener, DownloadFileDialog.DownloadFileListener,
151 DownloadImageDialog.DownloadImageListener, DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener,
152 EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener,
153 PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
155 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`,
156 // `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
157 // `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`,
158 // and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
159 public static boolean darkTheme;
161 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
162 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
163 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
164 public static Bitmap favoriteIconBitmap;
166 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
167 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
168 public static String formattedUrlString;
170 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
171 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
172 public static SslCertificate sslCertificate;
174 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
175 public static String orbotStatus;
177 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
178 public static String webViewTitle;
180 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
181 public static String appliedUserAgentString;
183 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
184 public static boolean reloadOnRestart;
186 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
187 public static boolean loadUrlOnRestart;
189 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
190 public static boolean restartFromBookmarksActivity;
192 // The block list versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
193 public static String easyListVersion;
194 public static String easyPrivacyVersion;
195 public static String fanboyAnnoyanceVersion;
196 public static String fanboySocialVersion;
198 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
199 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
200 public static String currentBookmarksFolder;
202 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
203 public static int domainSettingsDatabaseId;
205 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
206 public static String pinnedDomainSslIssuedToCNameString;
207 public static String pinnedDomainSslIssuedToONameString;
208 public static String pinnedDomainSslIssuedToUNameString;
209 public static String pinnedDomainSslIssuedByCNameString;
210 public static String pinnedDomainSslIssuedByONameString;
211 public static String pinnedDomainSslIssuedByUNameString;
212 public static Date pinnedDomainSslStartDate;
213 public static Date pinnedDomainSslEndDate;
216 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
217 private ActionBar appBar;
219 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
220 private boolean navigatingHistory;
222 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
223 private Bitmap favoriteIconDefaultBitmap;
225 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
226 private DrawerLayout drawerLayout;
228 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
229 private CoordinatorLayout rootCoordinatorLayout;
231 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
232 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
233 private WebView mainWebView;
235 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
236 private FrameLayout fullScreenVideoFrameLayout;
238 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
239 private SwipeRefreshLayout swipeRefreshLayout;
241 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
242 private RelativeLayout urlAppBarRelativeLayout;
244 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
245 private ImageView favoriteIconImageView;
247 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
248 private CookieManager cookieManager;
250 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
251 private final Map<String, String> customHeaders = new HashMap<>();
253 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
254 private boolean javaScriptEnabled;
256 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
257 private boolean firstPartyCookiesEnabled;
259 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
260 private boolean thirdPartyCookiesEnabled;
262 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
263 private boolean domStorageEnabled;
265 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
266 private boolean saveFormDataEnabled;
268 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
269 private boolean nightMode;
271 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
272 private boolean swipeToRefreshEnabled;
274 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
275 private boolean displayWebpageImagesBoolean;
277 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
278 private String homepage;
280 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
281 private String searchURL;
283 // The block list variables are used in `onCreate()` and `applyAppSettings()`.
284 private boolean easyListEnabled;
285 private boolean easyPrivacyEnabled;
286 private boolean fanboysAnnoyanceListEnabled;
287 private boolean fanboysSocialBlockingListEnabled;
289 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
290 private Runtime privacyBrowserRuntime;
292 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
293 boolean proxyThroughOrbot;
295 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
296 private boolean incognitoModeEnabled;
298 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
299 private boolean fullScreenBrowsingModeEnabled;
301 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
302 private boolean inFullScreenBrowsingMode;
304 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
305 private boolean hideSystemBarsOnFullscreen;
307 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
308 private boolean translucentNavigationBarOnFullscreen;
310 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
311 private boolean reapplyDomainSettingsOnRestart;
313 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
314 private boolean reapplyAppSettingsOnRestart;
316 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
317 private String currentDomainName;
319 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
320 private boolean ignorePinnedSslCertificate;
322 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
323 private boolean waitingForOrbot;
325 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
326 private boolean domainSettingsApplied;
328 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
329 private int displayWebpageImagesInt;
331 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
332 private boolean onTheFlyDisplayImagesSet;
334 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
335 private String waitingForOrbotHTMLString;
337 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
338 private String privateDataDirectoryString;
340 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
341 private LinearLayout findOnPageLinearLayout;
343 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
344 private EditText findOnPageEditText;
346 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
347 private Menu mainMenu;
349 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
350 private ActionBarDrawerToggle drawerToggle;
352 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
353 private Toolbar supportAppBar;
355 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
356 private EditText urlTextBox;
358 // The color spans are used in `onCreate()` and `highlightUrlText()`.
359 private ForegroundColorSpan redColorSpan;
360 private ForegroundColorSpan initialGrayColorSpan;
361 private ForegroundColorSpan finalGrayColorSpan;
363 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
366 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
367 private SslErrorHandler sslErrorHandler;
369 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
370 private static HttpAuthHandler httpAuthHandler;
372 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
373 private InputMethodManager inputMethodManager;
375 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
376 private RelativeLayout mainWebViewRelativeLayout;
378 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
379 private boolean urlIsLoading;
381 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
382 private boolean pinnedDomainSslCertificate;
384 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
385 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
387 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
388 private ListView bookmarksListView;
390 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
391 private TextView bookmarksTitleTextView;
393 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
394 private Cursor bookmarksCursor;
396 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
397 private CursorAdapter bookmarksCursorAdapter;
399 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
400 private String oldFolderNameString;
402 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
403 private String downloadUrl;
404 private String downloadContentDisposition;
405 private long downloadContentLength;
407 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
408 private String downloadImageUrl;
410 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
411 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
412 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
415 // 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.
416 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
417 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
418 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
419 @SuppressWarnings("deprecation")
420 protected void onCreate(Bundle savedInstanceState) {
421 // Get a handle for `sharedPreferences`. `this` references the current context.
422 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
424 // Get the theme preference.
425 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
427 // Set the activity theme.
429 setTheme(R.style.PrivacyBrowserDark);
431 setTheme(R.style.PrivacyBrowserLight);
434 // Run the default commands.
435 super.onCreate(savedInstanceState);
437 // Set the content view.
438 setContentView(R.layout.main_drawerlayout);
440 // Get a handle for `inputMethodManager`.
441 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
443 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
444 supportAppBar = findViewById(R.id.app_bar);
445 setSupportActionBar(supportAppBar);
446 appBar = getSupportActionBar();
448 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
449 assert appBar != null;
451 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
452 appBar.setCustomView(R.layout.url_app_bar);
453 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
455 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
456 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
457 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
458 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
460 // Get a handle for `urlTextBox`.
461 urlTextBox = findViewById(R.id.url_edittext);
463 // Remove the formatting from `urlTextBar` when the user is editing the text.
464 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
465 if (hasFocus) { // The user is editing `urlTextBox`.
466 // Remove the highlighting.
467 urlTextBox.getText().removeSpan(redColorSpan);
468 urlTextBox.getText().removeSpan(initialGrayColorSpan);
469 urlTextBox.getText().removeSpan(finalGrayColorSpan);
470 } else { // The user has stopped editing `urlTextBox`.
471 // Reapply the highlighting.
476 // Set the go button on the keyboard to load the URL in `urlTextBox`.
477 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
478 // If the event is a key-down event on the `enter` button, load the URL.
479 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
480 // Load the URL into the mainWebView and consume the event.
482 loadUrlFromTextBox();
483 } catch (UnsupportedEncodingException e) {
486 // If the enter key was pressed, consume the event.
489 // If any other key was pressed, do not consume the event.
494 // Set `waitingForOrbotHTMLString`.
495 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
497 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
498 currentDomainName = "";
499 orbotStatus = "unknown";
500 waitingForOrbot = false;
502 // Create an Orbot status `BroadcastReceiver`.
503 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
505 public void onReceive(Context context, Intent intent) {
506 // Store the content of the status message in `orbotStatus`.
507 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
509 // If we are waiting on Orbot, load the website now that Orbot is connected.
510 if (orbotStatus.equals("ON") && waitingForOrbot) {
511 // Reset `waitingForOrbot`.
512 waitingForOrbot = false;
514 // Load `formattedUrlString
515 loadUrl(formattedUrlString);
520 // Register `orbotStatusBroadcastReceiver` on `this` context.
521 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
523 // Get handles for views that need to be accessed.
524 drawerLayout = findViewById(R.id.drawerlayout);
525 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
526 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
527 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
528 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
529 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
530 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
531 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
532 mainWebView = findViewById(R.id.main_webview);
533 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
534 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
535 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
536 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
537 favoriteIconImageView = findViewById(R.id.favorite_icon);
539 // 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.
541 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
542 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
543 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
544 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
546 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
547 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
548 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
549 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
552 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
553 launchBookmarksActivityFab.setOnClickListener(v -> {
554 // Create an intent to launch the bookmarks activity.
555 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
557 // Include the current folder with the `Intent`.
558 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
561 startActivity(bookmarksIntent);
564 // Set the create new bookmark folder FAB to display the `AlertDialog`.
565 createBookmarkFolderFab.setOnClickListener(v -> {
566 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
567 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
568 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
571 // Set the create new bookmark FAB to display the `AlertDialog`.
572 createBookmarkFab.setOnClickListener(view -> {
573 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
574 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
575 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
578 // Create a double-tap listener to toggle full-screen mode.
579 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
580 // Override `onDoubleTap()`. All other events are handled using the default settings.
582 public boolean onDoubleTap(MotionEvent event) {
583 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
584 // Toggle `inFullScreenBrowsingMode`.
585 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
587 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
588 // Hide the `appBar`.
591 // Hide the `BannerAd` in the free flavor.
592 if (BuildConfig.FLAVOR.contentEquals("free")) {
593 BannerAd.hideAd(adView);
596 // Modify the system bars.
597 if (hideSystemBarsOnFullscreen) { // Hide everything.
598 // Remove the translucent overlays.
599 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
601 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
602 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
604 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
605 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
606 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
608 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
610 // Set `rootCoordinatorLayout` to fill the whole screen.
611 rootCoordinatorLayout.setFitsSystemWindows(false);
612 } else { // Hide everything except the status and navigation bars.
613 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
614 rootCoordinatorLayout.setFitsSystemWindows(false);
616 // 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.
617 if (translucentNavigationBarOnFullscreen) {
618 // Set the navigation bar to be translucent.
619 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
622 } else { // Switch to normal viewing mode.
623 // Show the `appBar`.
626 // Show the `BannerAd` in the free flavor.
627 if (BuildConfig.FLAVOR.contentEquals("free")) {
628 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
629 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
631 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
632 adView = findViewById(R.id.adview);
635 // Remove the translucent navigation bar flag if it is set.
636 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
638 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
639 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
641 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
642 rootCoordinatorLayout.setSystemUiVisibility(0);
644 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
645 rootCoordinatorLayout.setFitsSystemWindows(true);
648 // Consume the double-tap.
650 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
656 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
657 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
658 // Call `performClick()` on the view, which is required for accessibility.
661 // Send the `event` to `gestureDetector`.
662 return gestureDetector.onTouchEvent(event);
665 // Update `findOnPageCountTextView`.
666 mainWebView.setFindListener(new WebView.FindListener() {
667 // Get a handle for `findOnPageCountTextView`.
668 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
671 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
672 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
673 // Set `findOnPageCountTextView` to `0/0`.
674 findOnPageCountTextView.setText(R.string.zero_of_zero);
675 } else if (isDoneCounting) { // There are matches.
676 // `activeMatchOrdinal` is zero-based.
677 int activeMatch = activeMatchOrdinal + 1;
679 // Build the match string.
680 String matchString = activeMatch + "/" + numberOfMatches;
682 // Set `findOnPageCountTextView`.
683 findOnPageCountTextView.setText(matchString);
688 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
689 findOnPageEditText.addTextChangedListener(new TextWatcher() {
691 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
696 public void onTextChanged(CharSequence s, int start, int before, int count) {
701 public void afterTextChanged(Editable s) {
702 // Search for the text in `mainWebView`.
703 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
707 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
708 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
709 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
710 // Hide the soft keyboard. `0` indicates no additional flags.
711 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
713 // Consume the event.
715 } else { // A different key was pressed.
716 // Do not consume the event.
721 // Implement swipe to refresh
722 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
723 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
724 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
726 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
727 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
728 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
730 // Listen for touches on the navigation menu.
731 final NavigationView navigationView = findViewById(R.id.navigationview);
732 navigationView.setNavigationItemSelectedListener(this);
734 // 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.
735 final Menu navigationMenu = navigationView.getMenu();
736 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
737 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
738 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
740 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
741 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
742 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
744 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
745 currentBookmarksFolder = "";
747 // Load the home folder, which is `""` in the database.
748 loadBookmarksFolder();
750 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
751 // Convert the id from long to int to match the format of the bookmarks database.
752 int databaseID = (int) id;
754 // Get the bookmark `Cursor` for this ID and move it to the first row.
755 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
756 bookmarkCursor.moveToFirst();
758 // Act upon the bookmark according to the type.
759 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
760 // Store the new folder name in `currentBookmarksFolder`.
761 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
763 // Load the new folder.
764 loadBookmarksFolder();
765 } else { // The selected bookmark is not a folder.
766 // Load the bookmark URL.
767 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
769 // Close the bookmarks drawer.
770 drawerLayout.closeDrawer(GravityCompat.END);
773 // Close the `Cursor`.
774 bookmarkCursor.close();
777 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
778 // Convert the database ID from `long` to `int`.
779 int databaseId = (int) id;
781 // Find out if the selected bookmark is a folder.
782 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
785 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
786 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
788 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
789 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
790 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
792 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
793 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
794 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
797 // Consume the event.
801 // The `DrawerListener` allows us to update the Navigation Menu.
802 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
804 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
808 public void onDrawerOpened(@NonNull View drawerView) {
812 public void onDrawerClosed(@NonNull View drawerView) {
816 public void onDrawerStateChanged(int newState) {
817 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
818 // Update the `Back`, `Forward`, and `History` menu items.
819 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
820 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
821 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
823 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
824 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
826 // Clear the focus from `urlTextBox` if it has it.
827 urlTextBox.clearFocus();
832 // drawerToggle creates the hamburger icon at the start of the AppBar.
833 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
835 // Get a handle for the progress bar.
836 final ProgressBar progressBar = findViewById(R.id.progress_bar);
838 mainWebView.setWebChromeClient(new WebChromeClient() {
839 // Update the progress bar when a page is loading.
841 public void onProgressChanged(WebView view, int progress) {
842 // Inject the night mode CSS if night mode is enabled.
844 // `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
845 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
846 // `border: none` removes all borders, which can also be used to underline text.
847 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
848 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
849 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
850 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
851 // Initialize a `Handler` to display `mainWebView`.
852 Handler displayWebViewHandler = new Handler();
854 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
855 Runnable displayWebViewRunnable = () -> {
856 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
857 if (progressBar.getVisibility() == View.GONE) {
858 mainWebView.setVisibility(View.VISIBLE);
862 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
863 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
867 // Update the progress bar.
868 progressBar.setProgress(progress);
870 // Set the visibility of the progress bar.
871 if (progress < 100) {
872 // Show the progress bar.
873 progressBar.setVisibility(View.VISIBLE);
875 // Hide the progress bar.
876 progressBar.setVisibility(View.GONE);
878 // Display `mainWebView` if night mode is disabled.
879 // 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
880 // currently enabled.
882 mainWebView.setVisibility(View.VISIBLE);
885 //Stop the `SwipeToRefresh` indicator if it is running
886 swipeRefreshLayout.setRefreshing(false);
890 // Set the favorite icon when it changes.
892 public void onReceivedIcon(WebView view, Bitmap icon) {
893 // Only update the favorite icon if the website has finished loading.
894 if (progressBar.getVisibility() == View.GONE) {
895 // Save a copy of the favorite icon.
896 favoriteIconBitmap = icon;
898 // Place the favorite icon in the appBar.
899 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
903 // Save a copy of the title when it changes.
905 public void onReceivedTitle(WebView view, String title) {
906 // Save a copy of the title.
907 webViewTitle = title;
910 // Enter full screen video
912 public void onShowCustomView(View view, CustomViewCallback callback) {
913 // Pause the ad if this is the free flavor.
914 if (BuildConfig.FLAVOR.contentEquals("free")) {
915 BannerAd.pauseAd(adView);
918 // Remove the translucent overlays.
919 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
921 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
922 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
924 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
925 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
926 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
928 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
930 // Set `rootCoordinatorLayout` to fill the entire screen.
931 rootCoordinatorLayout.setFitsSystemWindows(false);
933 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
934 fullScreenVideoFrameLayout.addView(view);
935 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
938 // Exit full screen video
939 public void onHideCustomView() {
940 // Hide `fullScreenVideoFrameLayout`.
941 fullScreenVideoFrameLayout.removeAllViews();
942 fullScreenVideoFrameLayout.setVisibility(View.GONE);
944 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
945 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
947 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
948 rootCoordinatorLayout.setFitsSystemWindows(true);
950 // Show the ad if this is the free flavor.
951 if (BuildConfig.FLAVOR.contentEquals("free")) {
952 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
953 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
955 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
956 adView = findViewById(R.id.adview);
961 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
962 registerForContextMenu(mainWebView);
964 // Allow the downloading of files.
965 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
966 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
967 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
968 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
970 // Store the variables for future use by `onRequestPermissionsResult()`.
972 downloadContentDisposition = contentDisposition;
973 downloadContentLength = contentLength;
975 // Show a dialog if the user has previously denied the permission.
976 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
977 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
978 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
980 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
981 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
982 } else { // Show the permission request directly.
983 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
984 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
986 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
987 // Get a handle for the download file alert dialog.
988 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
990 // Show the download file alert dialog.
991 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
995 // Allow pinch to zoom.
996 mainWebView.getSettings().setBuiltInZoomControls(true);
998 // Hide zoom controls.
999 mainWebView.getSettings().setDisplayZoomControls(false);
1001 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1002 mainWebView.getSettings().setUseWideViewPort(true);
1004 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1005 mainWebView.getSettings().setLoadWithOverviewMode(true);
1007 // Explicitly disable geolocation.
1008 mainWebView.getSettings().setGeolocationEnabled(false);
1010 // Initialize cookieManager.
1011 cookieManager = CookieManager.getInstance();
1013 // 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).
1014 customHeaders.put("X-Requested-With", "");
1016 // 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.
1017 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1019 // Get the intent that started the app.
1020 final Intent launchingIntent = getIntent();
1022 // Extract the launching intent data as `launchingIntentUriData`.
1023 final Uri launchingIntentUriData = launchingIntent.getData();
1025 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1026 if (launchingIntentUriData != null) {
1027 formattedUrlString = launchingIntentUriData.toString();
1030 // Get a handle for the `Runtime`.
1031 privacyBrowserRuntime = Runtime.getRuntime();
1033 // Store the application's private data directory.
1034 privateDataDirectoryString = getApplicationInfo().dataDir;
1035 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1037 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1038 inFullScreenBrowsingMode = false;
1040 // Initialize AdView for the free flavor.
1041 adView = findViewById(R.id.adview);
1043 // Initialize the privacy settings variables.
1044 javaScriptEnabled = false;
1045 firstPartyCookiesEnabled = false;
1046 thirdPartyCookiesEnabled = false;
1047 domStorageEnabled = false;
1048 saveFormDataEnabled = false;
1051 // Initialize `webViewTitle`.
1052 webViewTitle = getString(R.string.no_title);
1054 // Initialize `favoriteIconBitmap`. `ContextCompat` must be used until API >= 21.
1055 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1056 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1057 assert favoriteIconBitmapDrawable != null;
1058 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1060 // If the favorite icon is null, load the default.
1061 if (favoriteIconBitmap == null) {
1062 favoriteIconBitmap = favoriteIconDefaultBitmap;
1065 // Apply the app settings from the shared preferences.
1068 // Instantiate the block list helper.
1069 BlockListHelper blockListHelper = new BlockListHelper();
1071 // Parse the block lists.
1072 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1073 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1074 final ArrayList<List<String[]>> fanboyAnnoyance = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1075 final ArrayList<List<String[]>> fanboySocial = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1077 // Store the list versions.
1078 easyListVersion = easyList.get(0).get(0)[0];
1079 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1080 fanboyAnnoyanceVersion = fanboyAnnoyance.get(0).get(0)[0];
1081 fanboySocialVersion = fanboySocial.get(0).get(0)[0];
1083 mainWebView.setWebViewClient(new WebViewClient() {
1084 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1085 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1086 @SuppressWarnings("deprecation")
1088 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1089 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1090 // Apply the domain settings for the new URL.
1091 applyDomainSettings(url, true);
1093 // Returning false causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
1095 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1096 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1097 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1099 // Parse the url and set it as the data for the intent.
1100 emailIntent.setData(Uri.parse(url));
1102 // Open the email program in a new task instead of as part of Privacy Browser.
1103 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1106 startActivity(emailIntent);
1108 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1110 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1111 // Open the dialer and load the phone number, but wait for the user to place the call.
1112 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1114 // Add the phone number to the intent.
1115 dialIntent.setData(Uri.parse(url));
1117 // Open the dialer in a new task instead of as part of Privacy Browser.
1118 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1121 startActivity(dialIntent);
1123 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1125 } else { // Load a system chooser to select an app that can handle the URL.
1126 // Open an app that can handle the URL.
1127 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1129 // Add the URL to the intent.
1130 genericIntent.setData(Uri.parse(url));
1132 // List all apps that can handle the URL instead of just opening the first one.
1133 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1135 // Open the app in a new task instead of as part of Privacy Browser.
1136 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1138 // Start the app or display a snackbar if no app is available to handle the URL.
1140 startActivity(genericIntent);
1141 } catch (ActivityNotFoundException exception) {
1142 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1145 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1150 // Check requests against the block lists. The deprecated `shouldInterceptRequest` must be used until minimum API >= 21.
1151 @SuppressWarnings("deprecation")
1153 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1154 // Create an empty web resource response to be used if the resource request is blocked.
1155 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1157 // Check EasyList if it is enabled.
1158 if (easyListEnabled) {
1159 if (blockListHelper.isBlocked(formattedUrlString, url, easyList)) {
1160 // The resource request was blocked. Return an empty web resource response.
1161 return emptyWebResourceResponse;
1165 // Check EasyPrivacy if it is enabled.
1166 if (easyPrivacyEnabled) {
1167 if (blockListHelper.isBlocked(formattedUrlString, url, easyPrivacy)) {
1168 // The resource request was blocked. Return an empty web resource response.
1169 return emptyWebResourceResponse;
1173 // Check Fanboy’s Annoyance List if it is enabled.
1174 if (fanboysAnnoyanceListEnabled) {
1175 if (blockListHelper.isBlocked(formattedUrlString, url, fanboyAnnoyance)) {
1176 // The resource request was blocked. Return an empty web resource response.
1177 return emptyWebResourceResponse;
1179 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1180 if (blockListHelper.isBlocked(formattedUrlString, url, fanboySocial)) {
1181 // The resource request was blocked. Return an empty web resource response.
1182 return emptyWebResourceResponse;
1186 // The resource request has not been blocked. `return null` loads the requested resource.
1190 // Handle HTTP authentication requests.
1192 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1193 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1194 httpAuthHandler = handler;
1196 // Display the HTTP authentication dialog.
1197 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1198 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1201 // Update the URL in urlTextBox when the page starts to load.
1203 public void onPageStarted(WebView view, String url, Bitmap favicon) {// If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1205 mainWebView.setVisibility(View.INVISIBLE);
1208 // Hide the keyboard. `0` indicates no additional flags.
1209 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1211 // Check to see if we are waiting on Orbot.
1212 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1213 // 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.
1214 formattedUrlString = url;
1216 // Display the formatted URL text.
1217 urlTextBox.setText(formattedUrlString);
1219 // Apply text highlighting to `urlTextBox`.
1222 // Apply any custom domain settings if the URL was loaded by navigating history.
1223 if (navigatingHistory) {
1224 applyDomainSettings(url, true);
1227 // 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.
1228 urlIsLoading = true;
1232 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1234 public void onPageFinished(WebView view, String url) {
1235 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1236 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1237 cookieManager.flush();
1240 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1241 urlIsLoading = false;
1243 // Clear the cache and history if Incognito Mode is enabled.
1244 if (incognitoModeEnabled) {
1245 // Clear the cache. `true` includes disk files.
1246 mainWebView.clearCache(true);
1248 // Clear the back/forward history.
1249 mainWebView.clearHistory();
1251 // Manually delete cache folders.
1253 // Delete the main `cache` folder.
1254 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1256 // Delete the `app_webview` folder, which contains an additional `WebView` cache. See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1257 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1258 } catch (IOException e) {
1259 // Do nothing if an error is thrown.
1263 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1264 if (!waitingForOrbot) {
1265 // Check to see if `WebView` has set `url` to be `about:blank`.
1266 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1267 // Set `formattedUrlString` to `""`.
1268 formattedUrlString = "";
1270 urlTextBox.setText(formattedUrlString);
1272 // Request focus for `urlTextBox`.
1273 urlTextBox.requestFocus();
1275 // Display the keyboard.
1276 inputMethodManager.showSoftInput(urlTextBox, 0);
1278 // Apply the domain settings. This clears any settings from the previous domain.
1279 applyDomainSettings(formattedUrlString, true);
1280 } else { // `WebView` has loaded a webpage.
1281 // Set `formattedUrlString`.
1282 formattedUrlString = url;
1284 // Only update `urlTextBox` if the user is not typing in it.
1285 if (!urlTextBox.hasFocus()) {
1286 // Display the formatted URL text.
1287 urlTextBox.setText(formattedUrlString);
1289 // Apply text highlighting to `urlTextBox`.
1294 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1295 sslCertificate = mainWebView.getCertificate();
1297 // 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.
1298 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1299 // Initialize the current SSL certificate variables.
1300 String currentWebsiteIssuedToCName = "";
1301 String currentWebsiteIssuedToOName = "";
1302 String currentWebsiteIssuedToUName = "";
1303 String currentWebsiteIssuedByCName = "";
1304 String currentWebsiteIssuedByOName = "";
1305 String currentWebsiteIssuedByUName = "";
1306 Date currentWebsiteSslStartDate = null;
1307 Date currentWebsiteSslEndDate = null;
1310 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1311 if (sslCertificate != null) {
1312 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1313 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1314 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1315 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1316 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1317 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1318 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1319 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1322 // 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`.
1323 String currentWebsiteSslStartDateString = "";
1324 String currentWebsiteSslEndDateString = "";
1325 String pinnedDomainSslStartDateString = "";
1326 String pinnedDomainSslEndDateString = "";
1328 // Convert the `Dates` to `Strings` if they are not `null`.
1329 if (currentWebsiteSslStartDate != null) {
1330 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1333 if (currentWebsiteSslEndDate != null) {
1334 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1337 if (pinnedDomainSslStartDate != null) {
1338 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1341 if (pinnedDomainSslEndDate != null) {
1342 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1345 // Check to see if the pinned SSL certificate matches the current website certificate.
1346 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1347 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1348 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1349 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1350 // The pinned SSL certificate doesn't match the current domain certificate.
1351 //Display the pinned SSL certificate mismatch `AlertDialog`.
1352 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1353 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1359 // Handle SSL Certificate errors.
1361 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1362 // Get the current website SSL certificate.
1363 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1365 // Extract the individual pieces of information from the current website SSL certificate.
1366 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1367 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1368 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1369 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1370 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1371 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1372 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1373 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1375 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1376 if (pinnedDomainSslCertificate &&
1377 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1378 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1379 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1380 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1381 // An SSL certificate is pinned and matches the current domain certificate.
1382 // Proceed to the website without displaying an error.
1384 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1385 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1386 sslErrorHandler = handler;
1388 // Display the SSL error `AlertDialog`.
1389 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1390 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1395 // Load the website if not waiting for Orbot to connect.
1396 if (!waitingForOrbot) {
1397 loadUrl(formattedUrlString);
1402 protected void onNewIntent(Intent intent) {
1403 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1406 // Check to see if the intent contains a new URL.
1407 if (intent.getData() != null) {
1408 // Get the intent data and convert it to a string.
1409 final Uri intentUriData = intent.getData();
1410 formattedUrlString = intentUriData.toString();
1412 // Load the website.
1413 loadUrl(formattedUrlString);
1415 // Close the navigation drawer if it is open.
1416 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1417 drawerLayout.closeDrawer(GravityCompat.START);
1420 // Close the bookmarks drawer if it is open.
1421 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1422 drawerLayout.closeDrawer(GravityCompat.END);
1425 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1426 mainWebView.requestFocus();
1431 public void onRestart() {
1432 // Run the default commands.
1435 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1436 if (proxyThroughOrbot) {
1437 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1438 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1440 // Send the intent to the Orbot package.
1441 orbotIntent.setPackage("org.torproject.android");
1444 sendBroadcast(orbotIntent);
1447 // Apply the app settings if returning from the Settings activity..
1448 if (reapplyAppSettingsOnRestart) {
1449 // Apply the app settings.
1452 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1453 if (reloadOnRestart) {
1454 // Reload `mainWebView`.
1455 mainWebView.reload();
1457 // Reset `reloadOnRestartBoolean`.
1458 reloadOnRestart = false;
1461 // Reset the return from settings flag.
1462 reapplyAppSettingsOnRestart = false;
1465 // Apply the domain settings if returning from the Domains activity.
1466 if (reapplyDomainSettingsOnRestart) {
1467 // Reapply the domain settings.
1468 applyDomainSettings(formattedUrlString, false);
1470 // Reset `reapplyDomainSettingsOnRestart`.
1471 reapplyDomainSettingsOnRestart = false;
1474 // Load the URL on restart to apply changes to night mode.
1475 if (loadUrlOnRestart) {
1476 // Load the current `formattedUrlString`.
1477 loadUrl(formattedUrlString);
1479 // Reset `loadUrlOnRestart.
1480 loadUrlOnRestart = false;
1483 // Update the bookmarks drawer if returning from the Bookmarks activity.
1484 if (restartFromBookmarksActivity) {
1485 // Close the bookmarks drawer.
1486 drawerLayout.closeDrawer(GravityCompat.END);
1488 // Reload the bookmarks drawer.
1489 loadBookmarksFolder();
1491 // Reset `restartFromBookmarksActivity`.
1492 restartFromBookmarksActivity = false;
1495 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1496 updatePrivacyIcons(true);
1499 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1501 public void onResume() {
1502 // Run the default commands.
1505 // Resume JavaScript (if enabled).
1506 mainWebView.resumeTimers();
1508 // Resume `mainWebView`.
1509 mainWebView.onResume();
1511 // Resume the adView for the free flavor.
1512 if (BuildConfig.FLAVOR.contentEquals("free")) {
1513 BannerAd.resumeAd(adView);
1518 public void onPause() {
1519 // Pause `mainWebView`.
1520 mainWebView.onPause();
1522 // Stop all JavaScript.
1523 mainWebView.pauseTimers();
1525 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1526 if (BuildConfig.FLAVOR.contentEquals("free")) {
1527 BannerAd.pauseAd(adView);
1534 public boolean onCreateOptionsMenu(Menu menu) {
1535 // Inflate the menu; this adds items to the action bar if it is present.
1536 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1538 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1541 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1542 updatePrivacyIcons(false);
1544 // Get handles for the menu items.
1545 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1546 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1547 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1548 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1550 // Only display third-party cookies if SDK >= 21
1551 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1553 // Get the shared preference values. `this` references the current context.
1554 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1556 // Set the status of the additional app bar icons. The default is `false`.
1557 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1558 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1559 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1560 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1561 } else { //Do not display the additional icons.
1562 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1563 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1564 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1571 public boolean onPrepareOptionsMenu(Menu menu) {
1572 // Get handles for the menu items.
1573 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1574 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1575 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1576 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1577 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1578 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1579 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1580 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1581 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1582 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1583 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1584 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1586 // Set the text for the domain menu item.
1587 if (domainSettingsApplied) {
1588 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1590 addOrEditDomain.setTitle(R.string.add_domain_settings);
1593 // Set the status of the menu item checkboxes.
1594 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1595 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1596 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1597 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1598 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1600 // Enable third-party cookies if first-party cookies are enabled.
1601 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1603 // Enable `DOM Storage` if JavaScript is enabled.
1604 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1606 // Enable `Clear Cookies` if there are any.
1607 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1609 // Get a count of the number of files in the `Local Storage` directory.
1610 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1611 int localStorageDirectoryNumberOfFiles = 0;
1612 if (localStorageDirectory.exists()) {
1613 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1616 // Get a count of the number of files in the `IndexedDB` directory.
1617 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1618 int indexedDBDirectoryNumberOfFiles = 0;
1619 if (indexedDBDirectory.exists()) {
1620 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1623 // Enable `Clear DOM Storage` if there is any.
1624 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1626 // Enable `Clear Form Data` is there is any.
1627 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1628 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1630 // Enable `Clear Data` if any of the submenu items are enabled.
1631 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1633 // Initialize font size variables.
1634 int fontSize = mainWebView.getSettings().getTextZoom();
1635 String fontSizeTitle;
1636 MenuItem selectedFontSizeMenuItem;
1638 // Prepare the font size title and current size menu item.
1641 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1642 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1646 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1647 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1651 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1652 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1656 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1657 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1661 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1662 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1666 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1667 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1671 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1672 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1676 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1677 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1681 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1682 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1686 // Set the font size title and select the current size menu item.
1687 fontSizeMenuItem.setTitle(fontSizeTitle);
1688 selectedFontSizeMenuItem.setChecked(true);
1690 // Only show `Refresh` if `swipeToRefresh` is disabled.
1691 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1693 // Run all the other default commands.
1694 super.onPrepareOptionsMenu(menu);
1696 // Display the menu.
1701 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1702 @SuppressLint("SetJavaScriptEnabled")
1703 // removeAllCookies is deprecated, but it is required for API < 21.
1704 @SuppressWarnings("deprecation")
1705 public boolean onOptionsItemSelected(MenuItem menuItem) {
1706 // Get the selected menu item ID.
1707 int menuItemId = menuItem.getItemId();
1709 // Set the commands that relate to the menu entries.
1710 switch (menuItemId) {
1711 case R.id.add_or_edit_domain:
1712 if (domainSettingsApplied) { // Edit the current domain settings.
1713 // Reapply the domain settings on returning to `MainWebViewActivity`.
1714 reapplyDomainSettingsOnRestart = true;
1715 currentDomainName = "";
1717 // Create an intent to launch the domains activity.
1718 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1720 // Put extra information instructing the domains activity to directly load the current domain.
1721 domainsIntent.putExtra("LoadDomain", domainSettingsDatabaseId);
1724 startActivity(domainsIntent);
1725 } else { // Add a new domain.
1726 // Show the add domain `AlertDialog`.
1727 AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
1728 addDomainDialog.show(getSupportFragmentManager(), getResources().getString(R.string.add_domain));
1732 case R.id.toggle_javascript:
1733 // Switch the status of javaScriptEnabled.
1734 javaScriptEnabled = !javaScriptEnabled;
1736 // Apply the new JavaScript status.
1737 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1739 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1740 updatePrivacyIcons(true);
1742 // Display a `Snackbar`.
1743 if (javaScriptEnabled) { // JavaScrip is enabled.
1744 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1745 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1746 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1747 } else { // Privacy mode.
1748 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1751 // Reload the WebView.
1752 mainWebView.reload();
1755 case R.id.toggle_first_party_cookies:
1756 // Switch the status of firstPartyCookiesEnabled.
1757 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1759 // Update the menu checkbox.
1760 menuItem.setChecked(firstPartyCookiesEnabled);
1762 // Apply the new cookie status.
1763 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1765 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1766 updatePrivacyIcons(true);
1768 // Display a `Snackbar`.
1769 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1770 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1771 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1772 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1773 } else { // Privacy mode.
1774 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1777 // Reload the WebView.
1778 mainWebView.reload();
1781 case R.id.toggle_third_party_cookies:
1782 if (Build.VERSION.SDK_INT >= 21) {
1783 // Switch the status of thirdPartyCookiesEnabled.
1784 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1786 // Update the menu checkbox.
1787 menuItem.setChecked(thirdPartyCookiesEnabled);
1789 // Apply the new cookie status.
1790 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1792 // Display a `Snackbar`.
1793 if (thirdPartyCookiesEnabled) {
1794 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1796 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1799 // Reload the WebView.
1800 mainWebView.reload();
1801 } // Else do nothing because SDK < 21.
1804 case R.id.toggle_dom_storage:
1805 // Switch the status of domStorageEnabled.
1806 domStorageEnabled = !domStorageEnabled;
1808 // Update the menu checkbox.
1809 menuItem.setChecked(domStorageEnabled);
1811 // Apply the new DOM Storage status.
1812 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1814 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1815 updatePrivacyIcons(true);
1817 // Display a `Snackbar`.
1818 if (domStorageEnabled) {
1819 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1821 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1824 // Reload the WebView.
1825 mainWebView.reload();
1828 case R.id.toggle_save_form_data:
1829 // Switch the status of saveFormDataEnabled.
1830 saveFormDataEnabled = !saveFormDataEnabled;
1832 // Update the menu checkbox.
1833 menuItem.setChecked(saveFormDataEnabled);
1835 // Apply the new form data status.
1836 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1838 // Display a `Snackbar`.
1839 if (saveFormDataEnabled) {
1840 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1842 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1845 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1846 updatePrivacyIcons(true);
1848 // Reload the WebView.
1849 mainWebView.reload();
1852 case R.id.clear_cookies:
1853 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1854 .setAction(R.string.undo, v -> {
1855 // Do nothing because everything will be handled by `onDismissed()` below.
1857 .addCallback(new Snackbar.Callback() {
1859 public void onDismissed(Snackbar snackbar, int event) {
1861 // The user pushed the `Undo` button.
1862 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1866 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1868 // `cookieManager.removeAllCookie()` varies by SDK.
1869 if (Build.VERSION.SDK_INT < 21) {
1870 cookieManager.removeAllCookie();
1872 // `null` indicates no callback.
1873 cookieManager.removeAllCookies(null);
1881 case R.id.clear_dom_storage:
1882 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1883 .setAction(R.string.undo, v -> {
1884 // Do nothing because everything will be handled by `onDismissed()` below.
1886 .addCallback(new Snackbar.Callback() {
1888 public void onDismissed(Snackbar snackbar, int event) {
1890 // The user pushed the `Undo` button.
1891 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1895 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1897 // Delete the DOM Storage.
1898 WebStorage webStorage = WebStorage.getInstance();
1899 webStorage.deleteAllData();
1901 // Manually delete the DOM storage files and directories.
1903 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1904 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1906 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1907 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1908 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1909 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1910 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1911 } catch (IOException e) {
1912 // Do nothing if an error is thrown.
1920 case R.id.clear_form_data:
1921 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1922 .setAction(R.string.undo, v -> {
1923 // Do nothing because everything will be handled by `onDismissed()` below.
1925 .addCallback(new Snackbar.Callback() {
1927 public void onDismissed(Snackbar snackbar, int event) {
1929 // The user pushed the `Undo` button.
1930 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1934 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1936 // Delete the form data.
1937 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1938 mainWebViewDatabase.clearFormData();
1945 case R.id.font_size_twenty_five_percent:
1946 mainWebView.getSettings().setTextZoom(25);
1949 case R.id.font_size_fifty_percent:
1950 mainWebView.getSettings().setTextZoom(50);
1953 case R.id.font_size_seventy_five_percent:
1954 mainWebView.getSettings().setTextZoom(75);
1957 case R.id.font_size_one_hundred_percent:
1958 mainWebView.getSettings().setTextZoom(100);
1961 case R.id.font_size_one_hundred_twenty_five_percent:
1962 mainWebView.getSettings().setTextZoom(125);
1965 case R.id.font_size_one_hundred_fifty_percent:
1966 mainWebView.getSettings().setTextZoom(150);
1969 case R.id.font_size_one_hundred_seventy_five_percent:
1970 mainWebView.getSettings().setTextZoom(175);
1973 case R.id.font_size_two_hundred_percent:
1974 mainWebView.getSettings().setTextZoom(200);
1977 case R.id.display_images:
1978 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1979 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1980 mainWebView.reload();
1981 } else { // Images are not currently loaded automatically.
1982 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1985 // Set `onTheFlyDisplayImagesSet`.
1986 onTheFlyDisplayImagesSet = true;
1990 // Setup the share string.
1991 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1993 // Create the share intent.
1994 Intent shareIntent = new Intent();
1995 shareIntent.setAction(Intent.ACTION_SEND);
1996 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1997 shareIntent.setType("text/plain");
2000 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2003 case R.id.find_on_page:
2004 // Hide the URL app bar.
2005 supportAppBar.setVisibility(View.GONE);
2007 // Show the Find on Page `RelativeLayout`.
2008 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2010 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2011 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2012 findOnPageEditText.postDelayed(() -> {
2013 // Set the focus on `findOnPageEditText`.
2014 findOnPageEditText.requestFocus();
2016 // Display the keyboard. `0` sets no input flags.
2017 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2022 // Get a `PrintManager` instance.
2023 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2025 // Convert `mainWebView` to `printDocumentAdapter`.
2026 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2028 // Remove the lint error below that `printManager` might be `null`.
2029 assert printManager != null;
2031 // Print the document. The print attributes are `null`.
2032 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2035 case R.id.view_source:
2036 // Launch the Vew Source activity.
2037 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2038 startActivity(viewSourceIntent);
2041 case R.id.add_to_homescreen:
2042 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2043 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2044 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2046 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2050 mainWebView.reload();
2054 // Don't consume the event.
2055 return super.onOptionsItemSelected(menuItem);
2059 // removeAllCookies is deprecated, but it is required for API < 21.
2060 @SuppressWarnings("deprecation")
2062 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2063 int menuItemId = menuItem.getItemId();
2065 switch (menuItemId) {
2071 if (mainWebView.canGoBack()) {
2072 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2073 navigatingHistory = true;
2075 // Load the previous website in the history.
2076 mainWebView.goBack();
2081 if (mainWebView.canGoForward()) {
2082 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2083 navigatingHistory = true;
2085 // Load the next website in the history.
2086 mainWebView.goForward();
2091 // Get the `WebBackForwardList`.
2092 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2094 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2095 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2096 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2099 case R.id.downloads:
2100 // Launch the system Download Manager.
2101 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2103 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2104 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2106 startActivity(downloadManagerIntent);
2110 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2111 reapplyDomainSettingsOnRestart = true;
2112 currentDomainName = "";
2114 // Launch `DomainsActivity`.
2115 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2116 startActivity(domainsIntent);
2120 // Set the flag to reapply app settings on restart when returning from Settings.
2121 reapplyAppSettingsOnRestart = true;
2123 // Set the flag to reapply the domain settings on restart when returning from Settings.
2124 reapplyDomainSettingsOnRestart = true;
2125 currentDomainName = "";
2127 // Launch `SettingsActivity`.
2128 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2129 startActivity(settingsIntent);
2133 // Launch `GuideActivity`.
2134 Intent guideIntent = new Intent(this, GuideActivity.class);
2135 startActivity(guideIntent);
2139 // Launch `AboutActivity`.
2140 Intent aboutIntent = new Intent(this, AboutActivity.class);
2141 startActivity(aboutIntent);
2144 case R.id.clearAndExit:
2145 // Get a handle for `sharedPreferences`. `this` references the current context.
2146 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2148 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2151 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2152 // The command to remove cookies changed slightly in API 21.
2153 if (Build.VERSION.SDK_INT >= 21) {
2154 cookieManager.removeAllCookies(null);
2156 cookieManager.removeAllCookie();
2159 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2161 // We have to use two commands because `Runtime.exec()` does not like `*`.
2162 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2163 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2164 } catch (IOException e) {
2165 // Do nothing if an error is thrown.
2169 // Clear DOM storage.
2170 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2171 // Ask `WebStorage` to clear the DOM storage.
2172 WebStorage webStorage = WebStorage.getInstance();
2173 webStorage.deleteAllData();
2175 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2177 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2178 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2180 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2181 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2182 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2183 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2184 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2185 } catch (IOException e) {
2186 // Do nothing if an error is thrown.
2191 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2192 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2193 webViewDatabase.clearFormData();
2195 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2197 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2198 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2199 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2200 } catch (IOException e) {
2201 // Do nothing if an error is thrown.
2206 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2207 // `true` includes disk files.
2208 mainWebView.clearCache(true);
2210 // Manually delete the cache directories.
2212 // Delete the main cache directory.
2213 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2214 // Delete the secondary `Service Worker` cache directory.
2215 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2216 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2217 } catch (IOException e) {
2218 // Do nothing if an error is thrown.
2222 // Clear SSL certificate preferences.
2223 mainWebView.clearSslPreferences();
2225 // Clear the back/forward history.
2226 mainWebView.clearHistory();
2228 // Clear `formattedUrlString`.
2229 formattedUrlString = null;
2231 // Clear `customHeaders`.
2232 customHeaders.clear();
2234 // Detach all views from `mainWebViewRelativeLayout`.
2235 mainWebViewRelativeLayout.removeAllViews();
2237 // Destroy the internal state of `mainWebView`.
2238 mainWebView.destroy();
2240 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2241 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2242 if (clearEverything) {
2244 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2245 } catch (IOException e) {
2246 // Do nothing if an error is thrown.
2250 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2251 if (Build.VERSION.SDK_INT >= 21) {
2252 finishAndRemoveTask();
2257 // Remove the terminated program from RAM. The status code is `0`.
2262 // Close the navigation drawer.
2263 drawerLayout.closeDrawer(GravityCompat.START);
2268 public void onPostCreate(Bundle savedInstanceState) {
2269 super.onPostCreate(savedInstanceState);
2271 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2272 drawerToggle.syncState();
2276 public void onConfigurationChanged(Configuration newConfig) {
2277 super.onConfigurationChanged(newConfig);
2279 // Reload the ad for the free flavor if we are not in full screen mode.
2280 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2282 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2284 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2285 adView = findViewById(R.id.adview);
2288 // `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:
2289 // https://code.google.com/p/android/issues/detail?id=20493#c8
2290 // ActivityCompat.invalidateOptionsMenu(this);
2294 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2295 // Store the `HitTestResult`.
2296 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2299 final String imageUrl;
2300 final String linkUrl;
2302 // Get a handle for the `ClipboardManager`.
2303 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2305 // Remove the lint errors below that `clipboardManager` might be `null`.
2306 assert clipboardManager != null;
2308 switch (hitTestResult.getType()) {
2309 // `SRC_ANCHOR_TYPE` is a link.
2310 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2311 // Get the target URL.
2312 linkUrl = hitTestResult.getExtra();
2314 // Set the target URL as the title of the `ContextMenu`.
2315 menu.setHeaderTitle(linkUrl);
2317 // Add a `Load URL` entry.
2318 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
2323 // Add a `Copy URL` entry.
2324 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2325 // Save the link URL in a `ClipData`.
2326 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2328 // Set the `ClipData` as the clipboard's primary clip.
2329 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2333 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2334 menu.add(R.string.cancel);
2337 case WebView.HitTestResult.EMAIL_TYPE:
2338 // Get the target URL.
2339 linkUrl = hitTestResult.getExtra();
2341 // Set the target URL as the title of the `ContextMenu`.
2342 menu.setHeaderTitle(linkUrl);
2344 // Add a `Write Email` entry.
2345 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2346 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2347 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2349 // Parse the url and set it as the data for the `Intent`.
2350 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2352 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2353 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2356 startActivity(emailIntent);
2360 // Add a `Copy Email Address` entry.
2361 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2362 // Save the email address in a `ClipData`.
2363 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2365 // Set the `ClipData` as the clipboard's primary clip.
2366 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2370 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2371 menu.add(R.string.cancel);
2374 // `IMAGE_TYPE` is an image.
2375 case WebView.HitTestResult.IMAGE_TYPE:
2376 // Get the image URL.
2377 imageUrl = hitTestResult.getExtra();
2379 // Set the image URL as the title of the `ContextMenu`.
2380 menu.setHeaderTitle(imageUrl);
2382 // Add a `View Image` entry.
2383 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2388 // Add a `Download Image` entry.
2389 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2390 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2391 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2392 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2394 // Store the image URL for use by `onRequestPermissionResult()`.
2395 downloadImageUrl = imageUrl;
2397 // Show a dialog if the user has previously denied the permission.
2398 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2399 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2400 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2402 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2403 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2404 } else { // Show the permission request directly.
2405 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2406 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2408 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2409 // Get a handle for the download image alert dialog.
2410 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2412 // Show the download image alert dialog.
2413 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2418 // Add a `Copy URL` entry.
2419 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2420 // Save the image URL in a `ClipData`.
2421 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2423 // Set the `ClipData` as the clipboard's primary clip.
2424 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2428 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2429 menu.add(R.string.cancel);
2433 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2434 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2435 // Get the image URL.
2436 imageUrl = hitTestResult.getExtra();
2438 // Set the image URL as the title of the `ContextMenu`.
2439 menu.setHeaderTitle(imageUrl);
2441 // Add a `View Image` entry.
2442 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2447 // Add a `Download Image` entry.
2448 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2449 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2450 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2451 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2453 // Store the image URL for use by `onRequestPermissionResult()`.
2454 downloadImageUrl = imageUrl;
2456 // Show a dialog if the user has previously denied the permission.
2457 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2458 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2459 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2461 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2462 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2463 } else { // Show the permission request directly.
2464 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2465 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2467 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2468 // Get a handle for the download image alert dialog.
2469 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2471 // Show the download image alert dialog.
2472 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2477 // Add a `Copy URL` entry.
2478 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2479 // Save the image URL in a `ClipData`.
2480 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2482 // Set the `ClipData` as the clipboard's primary clip.
2483 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2487 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2488 menu.add(R.string.cancel);
2494 public void onAddDomain(AppCompatDialogFragment dialogFragment) {
2495 // Reapply the domain settings on returning to `MainWebViewActivity`.
2496 reapplyDomainSettingsOnRestart = true;
2497 currentDomainName = "";
2499 // Get the new domain name `String` from `dialogFragment`.
2500 EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
2501 String domainNameString = domainNameEditText.getText().toString();
2503 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2504 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2505 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2507 // Create the domain and store the database ID in `currentDomainDatabaseId`.
2508 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
2510 // Create an intent to launch the domains activity.
2511 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2513 // Put extra information instructing the domains activity to directly load the current domain.
2514 domainsIntent.putExtra("LoadDomain", newDomainDatabaseId);
2517 startActivity(domainsIntent);
2521 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2522 // Get the `EditTexts` from the `dialogFragment`.
2523 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2524 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2526 // Extract the strings from the `EditTexts`.
2527 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2528 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2530 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2531 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2532 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2533 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2535 // Display the new bookmark below the current items in the (0 indexed) list.
2536 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2538 // Create the bookmark.
2539 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2541 // Update `bookmarksCursor` with the current contents of this folder.
2542 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2544 // Update the `ListView`.
2545 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2547 // Scroll to the new bookmark.
2548 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2552 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2553 // Get handles for the views in `dialogFragment`.
2554 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2555 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2556 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2558 // Get new folder name string.
2559 String folderNameString = createFolderNameEditText.getText().toString();
2561 // Get the new folder icon `Bitmap`.
2562 Bitmap folderIconBitmap;
2563 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2564 // Get the default folder icon and convert it to a `Bitmap`.
2565 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2566 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2567 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2568 } else { // Use the `WebView` favorite icon.
2569 folderIconBitmap = favoriteIconBitmap;
2572 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2573 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2574 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2575 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2577 // Move all the bookmarks down one in the display order.
2578 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2579 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2580 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2583 // Create the folder, which will be placed at the top of the `ListView`.
2584 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2586 // Update `bookmarksCursor` with the current contents of this folder.
2587 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2589 // Update the `ListView`.
2590 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2592 // Scroll to the new folder.
2593 bookmarksListView.setSelection(0);
2597 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2598 // Get the shortcut name.
2599 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2600 String shortcutNameString = shortcutNameEditText.getText().toString();
2602 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2603 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2605 // Setup the shortcut intent.
2606 Intent shortcutIntent = new Intent();
2607 shortcutIntent.setAction(Intent.ACTION_VIEW);
2608 shortcutIntent.setData(Uri.parse(formattedUrlString));
2610 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2611 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2613 // Add the required fields to the shortcut info builder.
2614 shortcutInfoBuilder.setIcon(favoriteIcon);
2615 shortcutInfoBuilder.setIntent(shortcutIntent);
2616 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2618 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2619 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2623 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2624 switch (downloadType) {
2625 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2626 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2627 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2630 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2631 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2632 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2638 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
2639 switch (requestCode) {
2640 case DOWNLOAD_FILE_REQUEST_CODE:
2641 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2642 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2644 // On API 23, displaying the fragment must be delayed or the app will crash.
2645 if (Build.VERSION.SDK_INT == 23) {
2646 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2648 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2651 // Reset the download variables.
2653 downloadContentDisposition = "";
2654 downloadContentLength = 0;
2657 case DOWNLOAD_IMAGE_REQUEST_CODE:
2658 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2659 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2661 // On API 23, displaying the fragment must be delayed or the app will crash.
2662 if (Build.VERSION.SDK_INT == 23) {
2663 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2665 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2668 // Reset the image URL variable.
2669 downloadImageUrl = "";
2675 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2676 // Download the image if it has an HTTP or HTTPS URI.
2677 if (imageUrl.startsWith("http")) {
2678 // Get a handle for the system `DOWNLOAD_SERVICE`.
2679 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2681 // Parse `imageUrl`.
2682 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2684 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2685 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2686 if (firstPartyCookiesEnabled) {
2687 // Get the cookies for `imageUrl`.
2688 String cookies = cookieManager.getCookie(imageUrl);
2690 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2691 downloadRequest.addRequestHeader("Cookie", cookies);
2694 // Get the file name from the dialog fragment.
2695 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2696 String imageName = downloadImageNameEditText.getText().toString();
2698 // Specify the download location.
2699 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2700 // Download to the public download directory.
2701 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2702 } else { // External write permission denied.
2703 // Download to the app's external download directory.
2704 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2707 // Allow `MediaScanner` to index the download if it is a media file.
2708 downloadRequest.allowScanningByMediaScanner();
2710 // Add the URL as the description for the download.
2711 downloadRequest.setDescription(imageUrl);
2713 // Show the download notification after the download is completed.
2714 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2716 // Remove the lint warning below that `downloadManager` might be `null`.
2717 assert downloadManager != null;
2719 // Initiate the download.
2720 downloadManager.enqueue(downloadRequest);
2721 } else { // The image is not an HTTP or HTTPS URI.
2722 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2727 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2728 // Download the file if it has an HTTP or HTTPS URI.
2729 if (downloadUrl.startsWith("http")) {
2730 // Get a handle for the system `DOWNLOAD_SERVICE`.
2731 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2733 // Parse `downloadUrl`.
2734 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2736 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2737 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2738 if (firstPartyCookiesEnabled) {
2739 // Get the cookies for `downloadUrl`.
2740 String cookies = cookieManager.getCookie(downloadUrl);
2742 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2743 downloadRequest.addRequestHeader("Cookie", cookies);
2746 // Get the file name from the dialog fragment.
2747 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2748 String fileName = downloadFileNameEditText.getText().toString();
2750 // Specify the download location.
2751 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2752 // Download to the public download directory.
2753 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2754 } else { // External write permission denied.
2755 // Download to the app's external download directory.
2756 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2759 // Allow `MediaScanner` to index the download if it is a media file.
2760 downloadRequest.allowScanningByMediaScanner();
2762 // Add the URL as the description for the download.
2763 downloadRequest.setDescription(downloadUrl);
2765 // Show the download notification after the download is completed.
2766 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2768 // Remove the lint warning below that `downloadManager` might be `null`.
2769 assert downloadManager != null;
2771 // Initiate the download.
2772 downloadManager.enqueue(downloadRequest);
2773 } else { // The download is not an HTTP or HTTPS URI.
2774 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2779 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2780 // Get handles for the views from `dialogFragment`.
2781 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2782 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2783 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2785 // Store the bookmark strings.
2786 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2787 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2789 // Update the bookmark.
2790 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2791 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2792 } else { // Update the bookmark using the `WebView` favorite icon.
2793 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2794 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2795 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2796 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2798 // Update the bookmark and the favorite icon.
2799 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2802 // Update `bookmarksCursor` with the current contents of this folder.
2803 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2805 // Update the `ListView`.
2806 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2810 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2811 // Get handles for the views from `dialogFragment`.
2812 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2813 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2814 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2815 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2817 // Get the new folder name.
2818 String newFolderNameString = editFolderNameEditText.getText().toString();
2820 // Check if the favorite icon has changed.
2821 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2822 // Update the name in the database.
2823 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2824 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2825 // Get the new folder icon `Bitmap`.
2826 Bitmap folderIconBitmap;
2827 if (defaultFolderIconRadioButton.isChecked()) {
2828 // Get the default folder icon and convert it to a `Bitmap`.
2829 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2830 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2831 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2832 } else { // Use the `WebView` favorite icon.
2833 folderIconBitmap = favoriteIconBitmap;
2836 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2837 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2838 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2839 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2841 // Update the folder icon in the database.
2842 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2843 } else { // The folder icon and the name have changed.
2844 // Get the new folder icon `Bitmap`.
2845 Bitmap folderIconBitmap;
2846 if (defaultFolderIconRadioButton.isChecked()) {
2847 // Get the default folder icon and convert it to a `Bitmap`.
2848 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2849 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2850 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2851 } else { // Use the `WebView` favorite icon.
2852 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2855 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2856 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2857 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2858 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2860 // Update the folder name and icon in the database.
2861 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2864 // Update `bookmarksCursor` with the current contents of this folder.
2865 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2867 // Update the `ListView`.
2868 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2872 public void onHttpAuthenticationCancel() {
2873 // Cancel the `HttpAuthHandler`.
2874 httpAuthHandler.cancel();
2878 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2879 // Get handles for the `EditTexts`.
2880 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2881 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2883 // Proceed with the HTTP authentication.
2884 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2887 public void viewSslCertificate(View view) {
2888 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2889 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2890 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2894 public void onSslErrorCancel() {
2895 sslErrorHandler.cancel();
2899 public void onSslErrorProceed() {
2900 sslErrorHandler.proceed();
2904 public void onSslMismatchBack() {
2905 if (mainWebView.canGoBack()) { // There is a back page in the history.
2906 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2907 navigatingHistory = true;
2910 mainWebView.goBack();
2911 } else { // There are no pages to go back to.
2912 // Load a blank page
2918 public void onSslMismatchProceed() {
2919 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2920 ignorePinnedSslCertificate = true;
2924 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2925 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2926 navigatingHistory = true;
2928 // Load the history entry.
2929 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2933 public void onClearHistory() {
2934 // Clear the history.
2935 mainWebView.clearHistory();
2938 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2940 public void onBackPressed() {
2941 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2942 // Close the navigation drawer.
2943 drawerLayout.closeDrawer(GravityCompat.START);
2944 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2945 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2946 // close the bookmarks drawer.
2947 drawerLayout.closeDrawer(GravityCompat.END);
2948 } else { // A subfolder is displayed.
2949 // Place the former parent folder in `currentFolder`.
2950 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2952 // Load the new folder.
2953 loadBookmarksFolder();
2956 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2957 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2958 navigatingHistory = true;
2961 mainWebView.goBack();
2962 } else { // There isn't anything to do in Privacy Browser.
2963 // Pass `onBackPressed()` to the system.
2964 super.onBackPressed();
2968 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2969 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2970 String unformattedUrlString = urlTextBox.getText().toString().trim();
2972 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2973 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2974 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2975 if (!unformattedUrlString.startsWith("http")) {
2976 unformattedUrlString = "http://" + unformattedUrlString;
2979 // Initialize `unformattedUrl`.
2980 URL unformattedUrl = null;
2982 // 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.
2984 unformattedUrl = new URL(unformattedUrlString);
2985 } catch (MalformedURLException e) {
2986 e.printStackTrace();
2989 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2990 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2991 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2992 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2993 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2994 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2997 Uri.Builder formattedUri = new Uri.Builder();
2998 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3000 // Decode `formattedUri` as a `String` in `UTF-8`.
3001 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3003 // Sanitize the search input and convert it to a search.
3004 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3006 // Add the base search URL.
3007 formattedUrlString = searchURL + encodedUrlString;
3010 // 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.
3011 urlTextBox.clearFocus();
3013 loadUrl(formattedUrlString);
3017 private void loadUrl(String url) {
3018 // Apply any custom domain settings.
3019 applyDomainSettings(url, true);
3022 mainWebView.loadUrl(url, customHeaders);
3024 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3025 urlIsLoading = true;
3028 public void findPreviousOnPage(View view) {
3029 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3030 mainWebView.findNext(false);
3033 public void findNextOnPage(View view) {
3034 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3035 mainWebView.findNext(true);
3038 public void closeFindOnPage(View view) {
3039 // Delete the contents of `find_on_page_edittext`.
3040 findOnPageEditText.setText(null);
3042 // Clear the highlighted phrases.
3043 mainWebView.clearMatches();
3045 // Hide the Find on Page `RelativeLayout`.
3046 findOnPageLinearLayout.setVisibility(View.GONE);
3048 // Show the URL app bar.
3049 supportAppBar.setVisibility(View.VISIBLE);
3051 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3052 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3055 private void applyAppSettings() {
3056 // Get a handle for the shared preferences.
3057 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3059 // Store the values from the shared preferences in variables.
3060 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3061 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3062 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3063 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3064 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3065 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3066 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3067 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3068 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3069 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3070 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3071 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3072 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
3073 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3075 // Set the homepage, search, and proxy options.
3076 if (proxyThroughOrbot) { // Set the Tor options.
3077 // Set `torHomepageString` as `homepage`.
3078 homepage = torHomepageString;
3080 // If formattedUrlString is null assign the homepage to it.
3081 if (formattedUrlString == null) {
3082 formattedUrlString = homepage;
3085 // Set the search URL.
3086 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3087 searchURL = torSearchCustomURLString;
3088 } else { // Use the string from the pre-built list.
3089 searchURL = torSearchString;
3092 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3093 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3095 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3097 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3099 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3102 // Display a message to the user if we are waiting on Orbot.
3103 if (!orbotStatus.equals("ON")) {
3104 // Set `waitingForOrbot`.
3105 waitingForOrbot = true;
3107 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3108 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3110 } else { // Set the non-Tor options.
3111 // Set `homepageString` as `homepage`.
3112 homepage = homepageString;
3114 // If formattedUrlString is null assign the homepage to it.
3115 if (formattedUrlString == null) {
3116 formattedUrlString = homepage;
3119 // Set the search URL.
3120 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3121 searchURL = searchCustomURLString;
3122 } else { // Use the string from the pre-built list.
3123 searchURL = searchString;
3126 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3127 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3129 // Set the default `appBar` background. `this` refers to the context.
3131 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3133 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3136 // Reset `waitingForOrbot.
3137 waitingForOrbot = false;
3140 // Set swipe to refresh.
3141 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
3143 // Set Do Not Track status.
3144 if (doNotTrackEnabled) {
3145 customHeaders.put("DNT", "1");
3147 customHeaders.remove("DNT");
3150 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3151 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3152 if (hideSystemBarsOnFullscreen) { // Hide everything.
3153 // Remove the translucent navigation setting if it is currently flagged.
3154 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3156 // Remove the translucent status bar overlay.
3157 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3159 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3160 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3162 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3163 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3164 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3166 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3167 } else { // Hide everything except the status and navigation bars.
3168 // Add the translucent status flag if it is unset.
3169 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3171 if (translucentNavigationBarOnFullscreen) {
3172 // Set the navigation bar to be translucent.
3173 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3175 // Set the navigation bar to be black.
3176 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3179 } else { // Switch to normal viewing mode.
3180 // Reset `inFullScreenBrowsingMode` to `false`.
3181 inFullScreenBrowsingMode = false;
3183 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3184 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3188 // Show the `BannerAd` in the free flavor.
3189 if (BuildConfig.FLAVOR.contentEquals("free")) {
3190 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
3191 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
3193 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3194 adView = findViewById(R.id.adview);
3197 // Remove the translucent navigation bar flag if it is set.
3198 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3200 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3201 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3203 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3204 rootCoordinatorLayout.setSystemUiVisibility(0);
3206 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3207 rootCoordinatorLayout.setFitsSystemWindows(true);
3212 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3213 @SuppressWarnings("deprecation")
3214 private void applyDomainSettings(String url, boolean resetFavoriteIcon) {
3215 // Reset `navigatingHistory`.
3216 navigatingHistory = false;
3218 // Parse the URL into a URI.
3219 Uri uri = Uri.parse(url);
3221 // Extract the domain from `uri`.
3222 String hostName = uri.getHost();
3224 // Initialize `loadingNewDomainName`.
3225 boolean loadingNewDomainName;
3227 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3228 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3229 //noinspection SimplifiableIfStatement
3230 if ((hostName == null) || (currentDomainName == null)) {
3231 loadingNewDomainName = true;
3232 } else { // Determine if `hostName` equals `currentDomainName`.
3233 loadingNewDomainName = !hostName.equals(currentDomainName);
3236 // 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.
3237 if (loadingNewDomainName) {
3238 // Set the new `hostname` as the `currentDomainName`.
3239 currentDomainName = hostName;
3241 // Reset `ignorePinnedSslCertificate`.
3242 ignorePinnedSslCertificate = false;
3244 // Reset the favorite icon if specified.
3245 if (resetFavoriteIcon) {
3246 favoriteIconBitmap = favoriteIconDefaultBitmap;
3247 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3250 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3251 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3252 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3254 // Get a full cursor from `domainsDatabaseHelper`.
3255 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3257 // Initialize `domainSettingsSet`.
3258 Set<String> domainSettingsSet = new HashSet<>();
3260 // Get the domain name column index.
3261 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3263 // Populate `domainSettingsSet`.
3264 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3265 // Move `domainsCursor` to the current row.
3266 domainNameCursor.moveToPosition(i);
3268 // Store the domain name in `domainSettingsSet`.
3269 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3272 // Close `domainNameCursor.
3273 domainNameCursor.close();
3275 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3276 domainSettingsApplied = false;
3277 String domainNameInDatabase = null;
3279 // Check the hostname.
3280 if (domainSettingsSet.contains(hostName)) {
3281 domainSettingsApplied = true;
3282 domainNameInDatabase = hostName;
3285 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3286 if (hostName != null) {
3287 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3288 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3289 domainSettingsApplied = true;
3290 domainNameInDatabase = "*." + hostName;
3293 // Strip out the lowest subdomain of `host`.
3294 hostName = hostName.substring(hostName.indexOf(".") + 1);
3298 // Get a handle for the shared preference. `this` references the current context.
3299 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3301 // Store the general preference information.
3302 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3303 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3304 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3305 nightMode = sharedPreferences.getBoolean("night_mode", false);
3307 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3308 // Get a cursor for the current host and move it to the first position.
3309 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3310 currentHostDomainSettingsCursor.moveToFirst();
3312 // Get the settings from the cursor.
3313 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3314 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3315 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3316 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3317 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3318 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3319 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3320 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3321 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3322 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3323 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3324 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3325 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3326 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3327 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3328 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3329 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3330 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3331 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3332 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3333 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3335 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3336 switch (nightModeInt) {
3337 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3341 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3346 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3348 javaScriptEnabled = true;
3351 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3352 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3353 pinnedDomainSslStartDate = null;
3355 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3358 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3359 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3360 pinnedDomainSslEndDate = null;
3362 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3365 // Close `currentHostDomainSettingsCursor`.
3366 currentHostDomainSettingsCursor.close();
3368 // Apply the domain settings.
3369 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3370 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3371 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3372 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3374 // Apply the font size.
3375 if (fontSize == 0) { // Apply the default font size.
3376 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3377 } else { // Apply the specified font size.
3378 mainWebView.getSettings().setTextZoom(fontSize);
3381 // Set third-party cookies status if API >= 21.
3382 if (Build.VERSION.SDK_INT >= 21) {
3383 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3386 // 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.
3387 // <https://redmine.stoutner.com/issues/160>
3388 if (!urlIsLoading) {
3389 switch (userAgentString) {
3390 case "System default user agent":
3391 // Set the user agent according to the system default.
3392 switch (defaultUserAgentString) {
3393 case "WebView default user agent":
3394 // Set the user agent to `""`, which uses the default value.
3395 mainWebView.getSettings().setUserAgentString("");
3398 case "Custom user agent":
3399 // Set the custom user agent.
3400 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3404 // Use the selected user agent.
3405 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3409 case "WebView default user agent":
3410 // Set the user agent to `""`, which uses the default value.
3411 mainWebView.getSettings().setUserAgentString("");
3415 // Use the selected user agent.
3416 mainWebView.getSettings().setUserAgentString(userAgentString);
3419 // Store the applied user agent string.
3420 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3423 // 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.
3425 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3427 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3429 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3430 // Store the values from `sharedPreferences` in variables.
3431 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3432 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3433 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3434 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3435 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3436 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3437 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3438 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3439 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3441 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3443 javaScriptEnabled = true;
3446 // Apply the default settings.
3447 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3448 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3449 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3450 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3451 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3453 // Reset the pinned SSL certificate information.
3454 domainSettingsDatabaseId = -1;
3455 pinnedDomainSslCertificate = false;
3456 pinnedDomainSslIssuedToCNameString = "";
3457 pinnedDomainSslIssuedToONameString = "";
3458 pinnedDomainSslIssuedToUNameString = "";
3459 pinnedDomainSslIssuedByCNameString = "";
3460 pinnedDomainSslIssuedByONameString = "";
3461 pinnedDomainSslIssuedByUNameString = "";
3462 pinnedDomainSslStartDate = null;
3463 pinnedDomainSslEndDate = null;
3465 // Set third-party cookies status if API >= 21.
3466 if (Build.VERSION.SDK_INT >= 21) {
3467 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3470 // 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.
3471 // <https://redmine.stoutner.com/issues/160>
3472 if (!urlIsLoading) {
3473 switch (defaultUserAgentString) {
3474 case "WebView default user agent":
3475 // Set the user agent to `""`, which uses the default value.
3476 mainWebView.getSettings().setUserAgentString("");
3479 case "Custom user agent":
3480 // Set the custom user agent.
3481 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3485 // Use the selected user agent.
3486 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3489 // Store the applied user agent string.
3490 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3493 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3494 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3497 // Close `domainsDatabaseHelper`.
3498 domainsDatabaseHelper.close();
3500 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3501 onTheFlyDisplayImagesSet = false;
3502 setDisplayWebpageImages();
3504 // Update the privacy icons, but only if `mainMenu` has already been populated.
3505 if (mainMenu != null) {
3506 updatePrivacyIcons(true);
3511 private void setDisplayWebpageImages() {
3512 if (!onTheFlyDisplayImagesSet) {
3513 if (domainSettingsApplied) { // Custom domain settings are applied.
3514 switch (displayWebpageImagesInt) {
3515 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3516 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3519 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3520 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3523 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3524 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3527 } else { // Default settings are applied.
3528 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3533 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3534 // Get handles for the icons.
3535 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3536 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3537 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3538 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3540 // Update `privacyIcon`.
3541 if (javaScriptEnabled) { // JavaScript is enabled.
3542 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3543 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3544 privacyIconMenuItem.setIcon(R.drawable.warning);
3545 } else { // All the dangerous features are disabled.
3546 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3549 // Update `firstPartyCookiesIcon`.
3550 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3551 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3552 } else { // First-party cookies are disabled.
3554 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3556 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3560 // Update `domStorageIcon`.
3561 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3562 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3563 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3565 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3567 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3569 } else { // JavaScript is disabled, so DOM storage is ghosted.
3571 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3573 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3577 // Update `formDataIcon`.
3578 if (saveFormDataEnabled) { // Form data is enabled.
3579 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3580 } else { // Form data is disabled.
3582 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3584 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3588 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3589 if (runInvalidateOptionsMenu) {
3590 invalidateOptionsMenu();
3594 private void highlightUrlText() {
3595 String urlString = urlTextBox.getText().toString();
3597 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3598 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3599 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3600 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3603 // Get the index of the `/` immediately after the domain name.
3604 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3606 // De-emphasize the text after the domain name.
3607 if (endOfDomainName > 0) {
3608 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3612 private void loadBookmarksFolder() {
3613 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3614 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3616 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3617 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3619 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3620 // Inflate the individual item layout. `false` does not attach it to the root.
3621 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3625 public void bindView(View view, Context context, Cursor cursor) {
3626 // Get handles for the views.
3627 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3628 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3630 // Get the favorite icon byte array from the `Cursor`.
3631 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3633 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3634 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3636 // Display the bitmap in `bookmarkFavoriteIcon`.
3637 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3639 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3640 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3641 bookmarkNameTextView.setText(bookmarkNameString);
3643 // Make the font bold for folders.
3644 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3645 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3646 } else { // Reset the font to default for normal bookmarks.
3647 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3652 // Populate the `ListView` with the adapter.
3653 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3655 // Set the bookmarks drawer title.
3656 if (currentBookmarksFolder.isEmpty()) {
3657 bookmarksTitleTextView.setText(R.string.bookmarks);
3659 bookmarksTitleTextView.setText(currentBookmarksFolder);