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 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
293 private boolean incognitoModeEnabled;
295 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
296 private boolean fullScreenBrowsingModeEnabled;
298 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
299 private boolean inFullScreenBrowsingMode;
301 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
302 private boolean hideSystemBarsOnFullscreen;
304 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
305 private boolean translucentNavigationBarOnFullscreen;
307 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
308 private boolean reapplyDomainSettingsOnRestart;
310 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
311 private boolean reapplyAppSettingsOnRestart;
313 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
314 private String currentDomainName;
316 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
317 private boolean ignorePinnedSslCertificate;
319 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
320 private boolean waitingForOrbot;
322 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
323 private boolean domainSettingsApplied;
325 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
326 private int displayWebpageImagesInt;
328 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
329 private boolean onTheFlyDisplayImagesSet;
331 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
332 private String waitingForOrbotHTMLString;
334 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
335 private String privateDataDirectoryString;
337 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
338 private LinearLayout findOnPageLinearLayout;
340 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
341 private EditText findOnPageEditText;
343 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
344 private Menu mainMenu;
346 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
347 private ActionBarDrawerToggle drawerToggle;
349 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
350 private Toolbar supportAppBar;
352 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
353 private EditText urlTextBox;
355 // The color spans are used in `onCreate()` and `highlightUrlText()`.
356 private ForegroundColorSpan redColorSpan;
357 private ForegroundColorSpan initialGrayColorSpan;
358 private ForegroundColorSpan finalGrayColorSpan;
360 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
363 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
364 private SslErrorHandler sslErrorHandler;
366 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
367 private static HttpAuthHandler httpAuthHandler;
369 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
370 private InputMethodManager inputMethodManager;
372 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
373 private RelativeLayout mainWebViewRelativeLayout;
375 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
376 private boolean urlIsLoading;
378 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
379 private boolean pinnedDomainSslCertificate;
381 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
382 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
384 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
385 private ListView bookmarksListView;
387 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
388 private TextView bookmarksTitleTextView;
390 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
391 private Cursor bookmarksCursor;
393 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
394 private CursorAdapter bookmarksCursorAdapter;
396 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
397 private String oldFolderNameString;
399 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
400 private String downloadUrl;
401 private String downloadContentDisposition;
402 private long downloadContentLength;
404 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
405 private String downloadImageUrl;
407 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
408 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
409 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
412 // 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.
413 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
414 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
415 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
416 @SuppressWarnings("deprecation")
417 protected void onCreate(Bundle savedInstanceState) {
418 // Get a handle for `sharedPreferences`. `this` references the current context.
419 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
421 // Get the theme preference.
422 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
424 // Set the activity theme.
426 setTheme(R.style.PrivacyBrowserDark);
428 setTheme(R.style.PrivacyBrowserLight);
431 // Run the default commands.
432 super.onCreate(savedInstanceState);
434 // Set the content view.
435 setContentView(R.layout.main_drawerlayout);
437 // Get a handle for `inputMethodManager`.
438 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
440 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
441 supportAppBar = findViewById(R.id.app_bar);
442 setSupportActionBar(supportAppBar);
443 appBar = getSupportActionBar();
445 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
446 assert appBar != null;
448 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
449 appBar.setCustomView(R.layout.url_app_bar);
450 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
452 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
453 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
454 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
455 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
457 // Get a handle for `urlTextBox`.
458 urlTextBox = findViewById(R.id.url_edittext);
460 // Remove the formatting from `urlTextBar` when the user is editing the text.
461 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
462 if (hasFocus) { // The user is editing `urlTextBox`.
463 // Remove the highlighting.
464 urlTextBox.getText().removeSpan(redColorSpan);
465 urlTextBox.getText().removeSpan(initialGrayColorSpan);
466 urlTextBox.getText().removeSpan(finalGrayColorSpan);
467 } else { // The user has stopped editing `urlTextBox`.
468 // Reapply the highlighting.
473 // Set the go button on the keyboard to load the URL in `urlTextBox`.
474 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
475 // If the event is a key-down event on the `enter` button, load the URL.
476 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
477 // Load the URL into the mainWebView and consume the event.
479 loadUrlFromTextBox();
480 } catch (UnsupportedEncodingException e) {
483 // If the enter key was pressed, consume the event.
486 // If any other key was pressed, do not consume the event.
491 // Set `waitingForOrbotHTMLString`.
492 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
494 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
495 currentDomainName = "";
496 orbotStatus = "unknown";
497 waitingForOrbot = false;
499 // Create an Orbot status `BroadcastReceiver`.
500 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
502 public void onReceive(Context context, Intent intent) {
503 // Store the content of the status message in `orbotStatus`.
504 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
506 // If we are waiting on Orbot, load the website now that Orbot is connected.
507 if (orbotStatus.equals("ON") && waitingForOrbot) {
508 // Reset `waitingForOrbot`.
509 waitingForOrbot = false;
511 // Load `formattedUrlString
512 loadUrl(formattedUrlString);
517 // Register `orbotStatusBroadcastReceiver` on `this` context.
518 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
520 // Get handles for views that need to be accessed.
521 drawerLayout = findViewById(R.id.drawerlayout);
522 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
523 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
524 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
525 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
526 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
527 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
528 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
529 mainWebView = findViewById(R.id.main_webview);
530 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
531 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
532 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
533 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
534 favoriteIconImageView = findViewById(R.id.favorite_icon);
536 // 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.
538 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
539 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
540 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
541 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
543 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
544 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
545 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
546 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
549 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
550 launchBookmarksActivityFab.setOnClickListener(v -> {
551 // Create an intent to launch the bookmarks activity.
552 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
554 // Include the current folder with the `Intent`.
555 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
558 startActivity(bookmarksIntent);
561 // Set the create new bookmark folder FAB to display the `AlertDialog`.
562 createBookmarkFolderFab.setOnClickListener(v -> {
563 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
564 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
565 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
568 // Set the create new bookmark FAB to display the `AlertDialog`.
569 createBookmarkFab.setOnClickListener(view -> {
570 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
571 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
572 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
575 // Create a double-tap listener to toggle full-screen mode.
576 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
577 // Override `onDoubleTap()`. All other events are handled using the default settings.
579 public boolean onDoubleTap(MotionEvent event) {
580 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
581 // Toggle `inFullScreenBrowsingMode`.
582 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
584 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
585 // Hide the `appBar`.
588 // Hide the `BannerAd` in the free flavor.
589 if (BuildConfig.FLAVOR.contentEquals("free")) {
590 BannerAd.hideAd(adView);
593 // Modify the system bars.
594 if (hideSystemBarsOnFullscreen) { // Hide everything.
595 // Remove the translucent overlays.
596 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
598 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
599 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
601 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
602 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
603 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
605 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
607 // Set `rootCoordinatorLayout` to fill the whole screen.
608 rootCoordinatorLayout.setFitsSystemWindows(false);
609 } else { // Hide everything except the status and navigation bars.
610 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
611 rootCoordinatorLayout.setFitsSystemWindows(false);
613 // 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.
614 if (translucentNavigationBarOnFullscreen) {
615 // Set the navigation bar to be translucent.
616 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
619 } else { // Switch to normal viewing mode.
620 // Show the `appBar`.
623 // Show the `BannerAd` in the free flavor.
624 if (BuildConfig.FLAVOR.contentEquals("free")) {
625 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
626 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
628 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
629 adView = findViewById(R.id.adview);
632 // Remove the translucent navigation bar flag if it is set.
633 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
635 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
636 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
638 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
639 rootCoordinatorLayout.setSystemUiVisibility(0);
641 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
642 rootCoordinatorLayout.setFitsSystemWindows(true);
645 // Consume the double-tap.
647 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
653 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
654 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
655 // Call `performClick()` on the view, which is required for accessibility.
658 // Send the `event` to `gestureDetector`.
659 return gestureDetector.onTouchEvent(event);
662 // Update `findOnPageCountTextView`.
663 mainWebView.setFindListener(new WebView.FindListener() {
664 // Get a handle for `findOnPageCountTextView`.
665 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
668 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
669 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
670 // Set `findOnPageCountTextView` to `0/0`.
671 findOnPageCountTextView.setText(R.string.zero_of_zero);
672 } else if (isDoneCounting) { // There are matches.
673 // `activeMatchOrdinal` is zero-based.
674 int activeMatch = activeMatchOrdinal + 1;
676 // Build the match string.
677 String matchString = activeMatch + "/" + numberOfMatches;
679 // Set `findOnPageCountTextView`.
680 findOnPageCountTextView.setText(matchString);
685 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
686 findOnPageEditText.addTextChangedListener(new TextWatcher() {
688 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
693 public void onTextChanged(CharSequence s, int start, int before, int count) {
698 public void afterTextChanged(Editable s) {
699 // Search for the text in `mainWebView`.
700 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
704 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
705 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
706 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
707 // Hide the soft keyboard. `0` indicates no additional flags.
708 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
710 // Consume the event.
712 } else { // A different key was pressed.
713 // Do not consume the event.
718 // Implement swipe to refresh
719 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
720 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
721 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
723 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
724 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
725 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
727 // Listen for touches on the navigation menu.
728 final NavigationView navigationView = findViewById(R.id.navigationview);
729 navigationView.setNavigationItemSelectedListener(this);
731 // 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.
732 final Menu navigationMenu = navigationView.getMenu();
733 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
734 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
735 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
737 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
738 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
739 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
741 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
742 currentBookmarksFolder = "";
744 // Load the home folder, which is `""` in the database.
745 loadBookmarksFolder();
747 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
748 // Convert the id from long to int to match the format of the bookmarks database.
749 int databaseID = (int) id;
751 // Get the bookmark `Cursor` for this ID and move it to the first row.
752 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
753 bookmarkCursor.moveToFirst();
755 // Act upon the bookmark according to the type.
756 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
757 // Store the new folder name in `currentBookmarksFolder`.
758 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
760 // Load the new folder.
761 loadBookmarksFolder();
762 } else { // The selected bookmark is not a folder.
763 // Load the bookmark URL.
764 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
766 // Close the bookmarks drawer.
767 drawerLayout.closeDrawer(GravityCompat.END);
770 // Close the `Cursor`.
771 bookmarkCursor.close();
774 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
775 // Convert the database ID from `long` to `int`.
776 int databaseId = (int) id;
778 // Find out if the selected bookmark is a folder.
779 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
782 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
783 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
785 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
786 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
787 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
789 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
790 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
791 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
794 // Consume the event.
798 // The `DrawerListener` allows us to update the Navigation Menu.
799 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
801 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
805 public void onDrawerOpened(@NonNull View drawerView) {
809 public void onDrawerClosed(@NonNull View drawerView) {
813 public void onDrawerStateChanged(int newState) {
814 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
815 // Update the `Back`, `Forward`, and `History` menu items.
816 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
817 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
818 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
820 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
821 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
823 // Clear the focus from `urlTextBox` if it has it.
824 urlTextBox.clearFocus();
829 // drawerToggle creates the hamburger icon at the start of the AppBar.
830 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
832 // Get a handle for the progress bar.
833 final ProgressBar progressBar = findViewById(R.id.progress_bar);
835 mainWebView.setWebChromeClient(new WebChromeClient() {
836 // Update the progress bar when a page is loading.
838 public void onProgressChanged(WebView view, int progress) {
839 // Inject the night mode CSS if night mode is enabled.
841 // `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
842 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
843 // `border: none` removes all borders, which can also be used to underline text.
844 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
845 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
846 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
847 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
848 // Initialize a `Handler` to display `mainWebView`.
849 Handler displayWebViewHandler = new Handler();
851 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
852 Runnable displayWebViewRunnable = () -> {
853 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
854 if (progressBar.getVisibility() == View.GONE) {
855 mainWebView.setVisibility(View.VISIBLE);
859 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
860 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
864 // Update the progress bar.
865 progressBar.setProgress(progress);
867 // Set the visibility of the progress bar.
868 if (progress < 100) {
869 // Show the progress bar.
870 progressBar.setVisibility(View.VISIBLE);
872 // Hide the progress bar.
873 progressBar.setVisibility(View.GONE);
875 // Display `mainWebView` if night mode is disabled.
876 // 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
877 // currently enabled.
879 mainWebView.setVisibility(View.VISIBLE);
882 //Stop the `SwipeToRefresh` indicator if it is running
883 swipeRefreshLayout.setRefreshing(false);
887 // Set the favorite icon when it changes.
889 public void onReceivedIcon(WebView view, Bitmap icon) {
890 // Only update the favorite icon if the website has finished loading.
891 if (progressBar.getVisibility() == View.GONE) {
892 // Save a copy of the favorite icon.
893 favoriteIconBitmap = icon;
895 // Place the favorite icon in the appBar.
896 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
900 // Save a copy of the title when it changes.
902 public void onReceivedTitle(WebView view, String title) {
903 // Save a copy of the title.
904 webViewTitle = title;
907 // Enter full screen video
909 public void onShowCustomView(View view, CustomViewCallback callback) {
910 // Pause the ad if this is the free flavor.
911 if (BuildConfig.FLAVOR.contentEquals("free")) {
912 BannerAd.pauseAd(adView);
915 // Remove the translucent overlays.
916 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
918 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
919 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
921 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
922 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
923 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
925 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
927 // Set `rootCoordinatorLayout` to fill the entire screen.
928 rootCoordinatorLayout.setFitsSystemWindows(false);
930 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
931 fullScreenVideoFrameLayout.addView(view);
932 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
935 // Exit full screen video
936 public void onHideCustomView() {
937 // Hide `fullScreenVideoFrameLayout`.
938 fullScreenVideoFrameLayout.removeAllViews();
939 fullScreenVideoFrameLayout.setVisibility(View.GONE);
941 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
942 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
944 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
945 rootCoordinatorLayout.setFitsSystemWindows(true);
947 // Show the ad if this is the free flavor.
948 if (BuildConfig.FLAVOR.contentEquals("free")) {
949 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
950 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
952 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
953 adView = findViewById(R.id.adview);
958 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
959 registerForContextMenu(mainWebView);
961 // Allow the downloading of files.
962 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
963 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
964 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
965 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
967 // Store the variables for future use by `onRequestPermissionsResult()`.
969 downloadContentDisposition = contentDisposition;
970 downloadContentLength = contentLength;
972 // Show a dialog if the user has previously denied the permission.
973 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
974 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
975 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
977 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
978 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
979 } else { // Show the permission request directly.
980 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
981 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
983 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
984 // Get a handle for the download file alert dialog.
985 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
987 // Show the download file alert dialog.
988 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
992 // Allow pinch to zoom.
993 mainWebView.getSettings().setBuiltInZoomControls(true);
995 // Hide zoom controls.
996 mainWebView.getSettings().setDisplayZoomControls(false);
998 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
999 mainWebView.getSettings().setUseWideViewPort(true);
1001 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1002 mainWebView.getSettings().setLoadWithOverviewMode(true);
1004 // Explicitly disable geolocation.
1005 mainWebView.getSettings().setGeolocationEnabled(false);
1007 // Initialize cookieManager.
1008 cookieManager = CookieManager.getInstance();
1010 // 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).
1011 customHeaders.put("X-Requested-With", "");
1013 // 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.
1014 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1016 // Get the intent that started the app.
1017 final Intent launchingIntent = getIntent();
1019 // Extract the launching intent data as `launchingIntentUriData`.
1020 final Uri launchingIntentUriData = launchingIntent.getData();
1022 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1023 if (launchingIntentUriData != null) {
1024 formattedUrlString = launchingIntentUriData.toString();
1027 // Get a handle for the `Runtime`.
1028 privacyBrowserRuntime = Runtime.getRuntime();
1030 // Store the application's private data directory.
1031 privateDataDirectoryString = getApplicationInfo().dataDir;
1032 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1034 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1035 inFullScreenBrowsingMode = false;
1037 // Initialize AdView for the free flavor.
1038 adView = findViewById(R.id.adview);
1040 // Initialize the privacy settings variables.
1041 javaScriptEnabled = false;
1042 firstPartyCookiesEnabled = false;
1043 thirdPartyCookiesEnabled = false;
1044 domStorageEnabled = false;
1045 saveFormDataEnabled = false;
1048 // Initialize `webViewTitle`.
1049 webViewTitle = getString(R.string.no_title);
1051 // Initialize `favoriteIconBitmap`. `ContextCompat` must be used until API >= 21.
1052 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1053 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1054 assert favoriteIconBitmapDrawable != null;
1055 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1057 // If the favorite icon is null, load the default.
1058 if (favoriteIconBitmap == null) {
1059 favoriteIconBitmap = favoriteIconDefaultBitmap;
1062 // Apply the app settings from the shared preferences.
1065 // Instantiate the block list helper.
1066 BlockListHelper blockListHelper = new BlockListHelper();
1068 // Parse the block lists.
1069 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1070 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1071 final ArrayList<List<String[]>> fanboyAnnoyance = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1072 final ArrayList<List<String[]>> fanboySocial = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1074 // Store the list versions.
1075 easyListVersion = easyList.get(0).get(0)[0];
1076 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1077 fanboyAnnoyanceVersion = fanboyAnnoyance.get(0).get(0)[0];
1078 fanboySocialVersion = fanboySocial.get(0).get(0)[0];
1080 mainWebView.setWebViewClient(new WebViewClient() {
1081 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1082 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1083 @SuppressWarnings("deprecation")
1085 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1086 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1087 // Apply the domain settings for the new URL.
1088 applyDomainSettings(url, true);
1090 // Returning false causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
1092 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1093 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1094 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1096 // Parse the url and set it as the data for the intent.
1097 emailIntent.setData(Uri.parse(url));
1099 // Open the email program in a new task instead of as part of Privacy Browser.
1100 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1103 startActivity(emailIntent);
1105 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1107 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1108 // Open the dialer and load the phone number, but wait for the user to place the call.
1109 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1111 // Add the phone number to the intent.
1112 dialIntent.setData(Uri.parse(url));
1114 // Open the dialer in a new task instead of as part of Privacy Browser.
1115 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1118 startActivity(dialIntent);
1120 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1122 } else { // Load a system chooser to select an app that can handle the URL.
1123 // Open an app that can handle the URL.
1124 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1126 // Add the URL to the intent.
1127 genericIntent.setData(Uri.parse(url));
1129 // List all apps that can handle the URL instead of just opening the first one.
1130 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1132 // Open the app in a new task instead of as part of Privacy Browser.
1133 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1135 // Start the app or display a snackbar if no app is available to handle the URL.
1137 startActivity(genericIntent);
1138 } catch (ActivityNotFoundException exception) {
1139 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1142 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1147 // Check requests against the block lists. The deprecated `shouldInterceptRequest` must be used until minimum API >= 21.
1148 @SuppressWarnings("deprecation")
1150 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1151 // Create an empty web resource response to be used if the resource request is blocked.
1152 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1154 // Check EasyList if it is enabled.
1155 if (easyListEnabled) {
1156 if (blockListHelper.isBlocked(formattedUrlString, url, easyList)) {
1157 // The resource request was blocked. Return an empty web resource response.
1158 return emptyWebResourceResponse;
1162 // Check EasyPrivacy if it is enabled.
1163 if (easyPrivacyEnabled) {
1164 if (blockListHelper.isBlocked(formattedUrlString, url, easyPrivacy)) {
1165 // The resource request was blocked. Return an empty web resource response.
1166 return emptyWebResourceResponse;
1170 // Check Fanboy’s Annoyance List if it is enabled.
1171 if (fanboysAnnoyanceListEnabled) {
1172 if (blockListHelper.isBlocked(formattedUrlString, url, fanboyAnnoyance)) {
1173 // The resource request was blocked. Return an empty web resource response.
1174 return emptyWebResourceResponse;
1176 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1177 if (blockListHelper.isBlocked(formattedUrlString, url, fanboySocial)) {
1178 // The resource request was blocked. Return an empty web resource response.
1179 return emptyWebResourceResponse;
1183 // The resource request has not been blocked. `return null` loads the requested resource.
1187 // Handle HTTP authentication requests.
1189 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1190 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1191 httpAuthHandler = handler;
1193 // Display the HTTP authentication dialog.
1194 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1195 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1198 // Update the URL in urlTextBox when the page starts to load.
1200 public void onPageStarted(WebView view, String url, Bitmap favicon) {// If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1202 mainWebView.setVisibility(View.INVISIBLE);
1205 // Hide the keyboard. `0` indicates no additional flags.
1206 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1208 // Check to see if we are waiting on Orbot.
1209 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1210 // 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.
1211 formattedUrlString = url;
1213 // Display the formatted URL text.
1214 urlTextBox.setText(formattedUrlString);
1216 // Apply text highlighting to `urlTextBox`.
1219 // Apply any custom domain settings if the URL was loaded by navigating history.
1220 if (navigatingHistory) {
1221 applyDomainSettings(url, true);
1224 // 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.
1225 urlIsLoading = true;
1229 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1231 public void onPageFinished(WebView view, String url) {
1232 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1233 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1234 cookieManager.flush();
1237 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1238 urlIsLoading = false;
1240 // Clear the cache and history if Incognito Mode is enabled.
1241 if (incognitoModeEnabled) {
1242 // Clear the cache. `true` includes disk files.
1243 mainWebView.clearCache(true);
1245 // Clear the back/forward history.
1246 mainWebView.clearHistory();
1248 // Manually delete cache folders.
1250 // Delete the main `cache` folder.
1251 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1253 // 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`.
1254 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1255 } catch (IOException e) {
1256 // Do nothing if an error is thrown.
1260 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1261 if (!waitingForOrbot) {
1262 // Check to see if `WebView` has set `url` to be `about:blank`.
1263 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1264 // Set `formattedUrlString` to `""`.
1265 formattedUrlString = "";
1267 urlTextBox.setText(formattedUrlString);
1269 // Request focus for `urlTextBox`.
1270 urlTextBox.requestFocus();
1272 // Display the keyboard.
1273 inputMethodManager.showSoftInput(urlTextBox, 0);
1275 // Apply the domain settings. This clears any settings from the previous domain.
1276 applyDomainSettings(formattedUrlString, true);
1277 } else { // `WebView` has loaded a webpage.
1278 // Set `formattedUrlString`.
1279 formattedUrlString = url;
1281 // Only update `urlTextBox` if the user is not typing in it.
1282 if (!urlTextBox.hasFocus()) {
1283 // Display the formatted URL text.
1284 urlTextBox.setText(formattedUrlString);
1286 // Apply text highlighting to `urlTextBox`.
1291 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1292 sslCertificate = mainWebView.getCertificate();
1294 // 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.
1295 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1296 // Initialize the current SSL certificate variables.
1297 String currentWebsiteIssuedToCName = "";
1298 String currentWebsiteIssuedToOName = "";
1299 String currentWebsiteIssuedToUName = "";
1300 String currentWebsiteIssuedByCName = "";
1301 String currentWebsiteIssuedByOName = "";
1302 String currentWebsiteIssuedByUName = "";
1303 Date currentWebsiteSslStartDate = null;
1304 Date currentWebsiteSslEndDate = null;
1307 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1308 if (sslCertificate != null) {
1309 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1310 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1311 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1312 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1313 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1314 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1315 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1316 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1319 // 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`.
1320 String currentWebsiteSslStartDateString = "";
1321 String currentWebsiteSslEndDateString = "";
1322 String pinnedDomainSslStartDateString = "";
1323 String pinnedDomainSslEndDateString = "";
1325 // Convert the `Dates` to `Strings` if they are not `null`.
1326 if (currentWebsiteSslStartDate != null) {
1327 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1330 if (currentWebsiteSslEndDate != null) {
1331 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1334 if (pinnedDomainSslStartDate != null) {
1335 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1338 if (pinnedDomainSslEndDate != null) {
1339 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1342 // Check to see if the pinned SSL certificate matches the current website certificate.
1343 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1344 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1345 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1346 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1347 // The pinned SSL certificate doesn't match the current domain certificate.
1348 //Display the pinned SSL certificate mismatch `AlertDialog`.
1349 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1350 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1356 // Handle SSL Certificate errors.
1358 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1359 // Get the current website SSL certificate.
1360 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1362 // Extract the individual pieces of information from the current website SSL certificate.
1363 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1364 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1365 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1366 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1367 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1368 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1369 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1370 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1372 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1373 if (pinnedDomainSslCertificate &&
1374 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1375 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1376 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1377 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1378 // An SSL certificate is pinned and matches the current domain certificate.
1379 // Proceed to the website without displaying an error.
1381 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1382 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1383 sslErrorHandler = handler;
1385 // Display the SSL error `AlertDialog`.
1386 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1387 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1392 // Load the website if not waiting for Orbot to connect.
1393 if (!waitingForOrbot) {
1394 loadUrl(formattedUrlString);
1399 protected void onNewIntent(Intent intent) {
1400 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1403 // Check to see if the intent contains a new URL.
1404 if (intent.getData() != null) {
1405 // Get the intent data and convert it to a string.
1406 final Uri intentUriData = intent.getData();
1407 formattedUrlString = intentUriData.toString();
1409 // Load the website.
1410 loadUrl(formattedUrlString);
1412 // Close the navigation drawer if it is open.
1413 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1414 drawerLayout.closeDrawer(GravityCompat.START);
1417 // Close the bookmarks drawer if it is open.
1418 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1419 drawerLayout.closeDrawer(GravityCompat.END);
1422 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1423 mainWebView.requestFocus();
1428 public void onRestart() {
1429 // Run the default commands.
1432 // Apply the app settings if returning from the Settings activity..
1433 if (reapplyAppSettingsOnRestart) {
1434 // Apply the app settings.
1437 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1438 if (reloadOnRestart) {
1439 // Reload `mainWebView`.
1440 mainWebView.reload();
1442 // Reset `reloadOnRestartBoolean`.
1443 reloadOnRestart = false;
1446 // Reset the return from settings flag.
1447 reapplyAppSettingsOnRestart = false;
1450 // Apply the domain settings if returning from the Domains activity.
1451 if (reapplyDomainSettingsOnRestart) {
1452 // Reapply the domain settings.
1453 applyDomainSettings(formattedUrlString, false);
1455 // Reset `reapplyDomainSettingsOnRestart`.
1456 reapplyDomainSettingsOnRestart = false;
1459 // Load the URL on restart to apply changes to night mode.
1460 if (loadUrlOnRestart) {
1461 // Load the current `formattedUrlString`.
1462 loadUrl(formattedUrlString);
1464 // Reset `loadUrlOnRestart.
1465 loadUrlOnRestart = false;
1468 // Update the bookmarks drawer if returning from the Bookmarks activity.
1469 if (restartFromBookmarksActivity) {
1470 // Close the bookmarks drawer.
1471 drawerLayout.closeDrawer(GravityCompat.END);
1473 // Reload the bookmarks drawer.
1474 loadBookmarksFolder();
1476 // Reset `restartFromBookmarksActivity`.
1477 restartFromBookmarksActivity = false;
1480 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1481 updatePrivacyIcons(true);
1484 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1486 public void onResume() {
1487 // Run the default commands.
1490 // Resume JavaScript (if enabled).
1491 mainWebView.resumeTimers();
1493 // Resume `mainWebView`.
1494 mainWebView.onResume();
1496 // Resume the adView for the free flavor.
1497 if (BuildConfig.FLAVOR.contentEquals("free")) {
1498 BannerAd.resumeAd(adView);
1503 public void onPause() {
1504 // Pause `mainWebView`.
1505 mainWebView.onPause();
1507 // Stop all JavaScript.
1508 mainWebView.pauseTimers();
1510 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1511 if (BuildConfig.FLAVOR.contentEquals("free")) {
1512 BannerAd.pauseAd(adView);
1519 public boolean onCreateOptionsMenu(Menu menu) {
1520 // Inflate the menu; this adds items to the action bar if it is present.
1521 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1523 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1526 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1527 updatePrivacyIcons(false);
1529 // Get handles for the menu items.
1530 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1531 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1532 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1533 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1535 // Only display third-party cookies if SDK >= 21
1536 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1538 // Get the shared preference values. `this` references the current context.
1539 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1541 // Set the status of the additional app bar icons. The default is `false`.
1542 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1543 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1544 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1545 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1546 } else { //Do not display the additional icons.
1547 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1548 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1549 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1556 public boolean onPrepareOptionsMenu(Menu menu) {
1557 // Get handles for the menu items.
1558 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1559 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1560 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1561 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1562 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1563 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1564 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1565 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1566 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1567 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1568 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1569 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1571 // Set the text for the domain menu item.
1572 if (domainSettingsApplied) {
1573 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1575 addOrEditDomain.setTitle(R.string.add_domain_settings);
1578 // Set the status of the menu item checkboxes.
1579 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1580 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1581 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1582 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1583 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1585 // Enable third-party cookies if first-party cookies are enabled.
1586 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1588 // Enable `DOM Storage` if JavaScript is enabled.
1589 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1591 // Enable `Clear Cookies` if there are any.
1592 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1594 // Get a count of the number of files in the `Local Storage` directory.
1595 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1596 int localStorageDirectoryNumberOfFiles = 0;
1597 if (localStorageDirectory.exists()) {
1598 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1601 // Get a count of the number of files in the `IndexedDB` directory.
1602 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1603 int indexedDBDirectoryNumberOfFiles = 0;
1604 if (indexedDBDirectory.exists()) {
1605 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1608 // Enable `Clear DOM Storage` if there is any.
1609 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1611 // Enable `Clear Form Data` is there is any.
1612 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1613 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1615 // Enable `Clear Data` if any of the submenu items are enabled.
1616 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1618 // Initialize font size variables.
1619 int fontSize = mainWebView.getSettings().getTextZoom();
1620 String fontSizeTitle;
1621 MenuItem selectedFontSizeMenuItem;
1623 // Prepare the font size title and current size menu item.
1626 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1627 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1631 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1632 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1636 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1637 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1641 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1642 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1646 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1647 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1651 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1652 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1656 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1657 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1661 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1662 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1666 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1667 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1671 // Set the font size title and select the current size menu item.
1672 fontSizeMenuItem.setTitle(fontSizeTitle);
1673 selectedFontSizeMenuItem.setChecked(true);
1675 // Only show `Refresh` if `swipeToRefresh` is disabled.
1676 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1678 // Run all the other default commands.
1679 super.onPrepareOptionsMenu(menu);
1681 // Display the menu.
1686 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1687 @SuppressLint("SetJavaScriptEnabled")
1688 // removeAllCookies is deprecated, but it is required for API < 21.
1689 @SuppressWarnings("deprecation")
1690 public boolean onOptionsItemSelected(MenuItem menuItem) {
1691 // Get the selected menu item ID.
1692 int menuItemId = menuItem.getItemId();
1694 // Set the commands that relate to the menu entries.
1695 switch (menuItemId) {
1696 case R.id.add_or_edit_domain:
1697 if (domainSettingsApplied) { // Edit the current domain settings.
1698 // Reapply the domain settings on returning to `MainWebViewActivity`.
1699 reapplyDomainSettingsOnRestart = true;
1700 currentDomainName = "";
1702 // Create an intent to launch the domains activity.
1703 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1705 // Put extra information instructing the domains activity to directly load the current domain.
1706 domainsIntent.putExtra("LoadDomain", domainSettingsDatabaseId);
1709 startActivity(domainsIntent);
1710 } else { // Add a new domain.
1711 // Show the add domain `AlertDialog`.
1712 AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
1713 addDomainDialog.show(getSupportFragmentManager(), getResources().getString(R.string.add_domain));
1717 case R.id.toggle_javascript:
1718 // Switch the status of javaScriptEnabled.
1719 javaScriptEnabled = !javaScriptEnabled;
1721 // Apply the new JavaScript status.
1722 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1724 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1725 updatePrivacyIcons(true);
1727 // Display a `Snackbar`.
1728 if (javaScriptEnabled) { // JavaScrip is enabled.
1729 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1730 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1731 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1732 } else { // Privacy mode.
1733 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1736 // Reload the WebView.
1737 mainWebView.reload();
1740 case R.id.toggle_first_party_cookies:
1741 // Switch the status of firstPartyCookiesEnabled.
1742 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1744 // Update the menu checkbox.
1745 menuItem.setChecked(firstPartyCookiesEnabled);
1747 // Apply the new cookie status.
1748 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1750 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1751 updatePrivacyIcons(true);
1753 // Display a `Snackbar`.
1754 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1755 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1756 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1757 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1758 } else { // Privacy mode.
1759 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1762 // Reload the WebView.
1763 mainWebView.reload();
1766 case R.id.toggle_third_party_cookies:
1767 if (Build.VERSION.SDK_INT >= 21) {
1768 // Switch the status of thirdPartyCookiesEnabled.
1769 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1771 // Update the menu checkbox.
1772 menuItem.setChecked(thirdPartyCookiesEnabled);
1774 // Apply the new cookie status.
1775 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1777 // Display a `Snackbar`.
1778 if (thirdPartyCookiesEnabled) {
1779 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1781 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1784 // Reload the WebView.
1785 mainWebView.reload();
1786 } // Else do nothing because SDK < 21.
1789 case R.id.toggle_dom_storage:
1790 // Switch the status of domStorageEnabled.
1791 domStorageEnabled = !domStorageEnabled;
1793 // Update the menu checkbox.
1794 menuItem.setChecked(domStorageEnabled);
1796 // Apply the new DOM Storage status.
1797 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1799 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1800 updatePrivacyIcons(true);
1802 // Display a `Snackbar`.
1803 if (domStorageEnabled) {
1804 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1806 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1809 // Reload the WebView.
1810 mainWebView.reload();
1813 case R.id.toggle_save_form_data:
1814 // Switch the status of saveFormDataEnabled.
1815 saveFormDataEnabled = !saveFormDataEnabled;
1817 // Update the menu checkbox.
1818 menuItem.setChecked(saveFormDataEnabled);
1820 // Apply the new form data status.
1821 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1823 // Display a `Snackbar`.
1824 if (saveFormDataEnabled) {
1825 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1827 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1830 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1831 updatePrivacyIcons(true);
1833 // Reload the WebView.
1834 mainWebView.reload();
1837 case R.id.clear_cookies:
1838 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1839 .setAction(R.string.undo, v -> {
1840 // Do nothing because everything will be handled by `onDismissed()` below.
1842 .addCallback(new Snackbar.Callback() {
1844 public void onDismissed(Snackbar snackbar, int event) {
1846 // The user pushed the `Undo` button.
1847 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1851 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1853 // `cookieManager.removeAllCookie()` varies by SDK.
1854 if (Build.VERSION.SDK_INT < 21) {
1855 cookieManager.removeAllCookie();
1857 // `null` indicates no callback.
1858 cookieManager.removeAllCookies(null);
1866 case R.id.clear_dom_storage:
1867 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1868 .setAction(R.string.undo, v -> {
1869 // Do nothing because everything will be handled by `onDismissed()` below.
1871 .addCallback(new Snackbar.Callback() {
1873 public void onDismissed(Snackbar snackbar, int event) {
1875 // The user pushed the `Undo` button.
1876 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1880 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1882 // Delete the DOM Storage.
1883 WebStorage webStorage = WebStorage.getInstance();
1884 webStorage.deleteAllData();
1886 // Manually delete the DOM storage files and directories.
1888 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1889 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1891 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1892 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1893 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1894 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1895 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1896 } catch (IOException e) {
1897 // Do nothing if an error is thrown.
1905 case R.id.clear_form_data:
1906 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1907 .setAction(R.string.undo, v -> {
1908 // Do nothing because everything will be handled by `onDismissed()` below.
1910 .addCallback(new Snackbar.Callback() {
1912 public void onDismissed(Snackbar snackbar, int event) {
1914 // The user pushed the `Undo` button.
1915 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1919 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1921 // Delete the form data.
1922 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1923 mainWebViewDatabase.clearFormData();
1930 case R.id.font_size_twenty_five_percent:
1931 mainWebView.getSettings().setTextZoom(25);
1934 case R.id.font_size_fifty_percent:
1935 mainWebView.getSettings().setTextZoom(50);
1938 case R.id.font_size_seventy_five_percent:
1939 mainWebView.getSettings().setTextZoom(75);
1942 case R.id.font_size_one_hundred_percent:
1943 mainWebView.getSettings().setTextZoom(100);
1946 case R.id.font_size_one_hundred_twenty_five_percent:
1947 mainWebView.getSettings().setTextZoom(125);
1950 case R.id.font_size_one_hundred_fifty_percent:
1951 mainWebView.getSettings().setTextZoom(150);
1954 case R.id.font_size_one_hundred_seventy_five_percent:
1955 mainWebView.getSettings().setTextZoom(175);
1958 case R.id.font_size_two_hundred_percent:
1959 mainWebView.getSettings().setTextZoom(200);
1962 case R.id.display_images:
1963 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1964 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1965 mainWebView.reload();
1966 } else { // Images are not currently loaded automatically.
1967 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1970 // Set `onTheFlyDisplayImagesSet`.
1971 onTheFlyDisplayImagesSet = true;
1975 // Setup the share string.
1976 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1978 // Create the share intent.
1979 Intent shareIntent = new Intent();
1980 shareIntent.setAction(Intent.ACTION_SEND);
1981 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1982 shareIntent.setType("text/plain");
1985 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1988 case R.id.find_on_page:
1989 // Hide the URL app bar.
1990 supportAppBar.setVisibility(View.GONE);
1992 // Show the Find on Page `RelativeLayout`.
1993 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1995 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1996 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1997 findOnPageEditText.postDelayed(() -> {
1998 // Set the focus on `findOnPageEditText`.
1999 findOnPageEditText.requestFocus();
2001 // Display the keyboard. `0` sets no input flags.
2002 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2007 // Get a `PrintManager` instance.
2008 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2010 // Convert `mainWebView` to `printDocumentAdapter`.
2011 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2013 // Remove the lint error below that `printManager` might be `null`.
2014 assert printManager != null;
2016 // Print the document. The print attributes are `null`.
2017 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2020 case R.id.view_source:
2021 // Launch the Vew Source activity.
2022 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2023 startActivity(viewSourceIntent);
2026 case R.id.add_to_homescreen:
2027 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2028 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2029 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2031 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2035 mainWebView.reload();
2039 // Don't consume the event.
2040 return super.onOptionsItemSelected(menuItem);
2044 // removeAllCookies is deprecated, but it is required for API < 21.
2045 @SuppressWarnings("deprecation")
2047 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2048 int menuItemId = menuItem.getItemId();
2050 switch (menuItemId) {
2056 if (mainWebView.canGoBack()) {
2057 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2058 navigatingHistory = true;
2060 // Load the previous website in the history.
2061 mainWebView.goBack();
2066 if (mainWebView.canGoForward()) {
2067 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2068 navigatingHistory = true;
2070 // Load the next website in the history.
2071 mainWebView.goForward();
2076 // Get the `WebBackForwardList`.
2077 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2079 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2080 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2081 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2084 case R.id.downloads:
2085 // Launch the system Download Manager.
2086 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2088 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2089 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2091 startActivity(downloadManagerIntent);
2095 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2096 reapplyDomainSettingsOnRestart = true;
2097 currentDomainName = "";
2099 // Launch `DomainsActivity`.
2100 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2101 startActivity(domainsIntent);
2105 // Set the flag to reapply app settings on restart when returning from Settings.
2106 reapplyAppSettingsOnRestart = true;
2108 // Set the flag to reapply the domain settings on restart when returning from Settings.
2109 reapplyDomainSettingsOnRestart = true;
2110 currentDomainName = "";
2112 // Launch `SettingsActivity`.
2113 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2114 startActivity(settingsIntent);
2118 // Launch `GuideActivity`.
2119 Intent guideIntent = new Intent(this, GuideActivity.class);
2120 startActivity(guideIntent);
2124 // Launch `AboutActivity`.
2125 Intent aboutIntent = new Intent(this, AboutActivity.class);
2126 startActivity(aboutIntent);
2129 case R.id.clearAndExit:
2130 // Get a handle for `sharedPreferences`. `this` references the current context.
2131 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2133 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2136 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2137 // The command to remove cookies changed slightly in API 21.
2138 if (Build.VERSION.SDK_INT >= 21) {
2139 cookieManager.removeAllCookies(null);
2141 cookieManager.removeAllCookie();
2144 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2146 // We have to use two commands because `Runtime.exec()` does not like `*`.
2147 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2148 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2149 } catch (IOException e) {
2150 // Do nothing if an error is thrown.
2154 // Clear DOM storage.
2155 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2156 // Ask `WebStorage` to clear the DOM storage.
2157 WebStorage webStorage = WebStorage.getInstance();
2158 webStorage.deleteAllData();
2160 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2162 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2163 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2165 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2166 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2167 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2168 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2169 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2170 } catch (IOException e) {
2171 // Do nothing if an error is thrown.
2176 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2177 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2178 webViewDatabase.clearFormData();
2180 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2182 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2183 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2184 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2185 } catch (IOException e) {
2186 // Do nothing if an error is thrown.
2191 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2192 // `true` includes disk files.
2193 mainWebView.clearCache(true);
2195 // Manually delete the cache directories.
2197 // Delete the main cache directory.
2198 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2199 // Delete the secondary `Service Worker` cache directory.
2200 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2201 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2202 } catch (IOException e) {
2203 // Do nothing if an error is thrown.
2207 // Clear SSL certificate preferences.
2208 mainWebView.clearSslPreferences();
2210 // Clear the back/forward history.
2211 mainWebView.clearHistory();
2213 // Clear `formattedUrlString`.
2214 formattedUrlString = null;
2216 // Clear `customHeaders`.
2217 customHeaders.clear();
2219 // Detach all views from `mainWebViewRelativeLayout`.
2220 mainWebViewRelativeLayout.removeAllViews();
2222 // Destroy the internal state of `mainWebView`.
2223 mainWebView.destroy();
2225 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2226 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2227 if (clearEverything) {
2229 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2230 } catch (IOException e) {
2231 // Do nothing if an error is thrown.
2235 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2236 if (Build.VERSION.SDK_INT >= 21) {
2237 finishAndRemoveTask();
2242 // Remove the terminated program from RAM. The status code is `0`.
2247 // Close the navigation drawer.
2248 drawerLayout.closeDrawer(GravityCompat.START);
2253 public void onPostCreate(Bundle savedInstanceState) {
2254 super.onPostCreate(savedInstanceState);
2256 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2257 drawerToggle.syncState();
2261 public void onConfigurationChanged(Configuration newConfig) {
2262 super.onConfigurationChanged(newConfig);
2264 // Reload the ad for the free flavor if we are not in full screen mode.
2265 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2267 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2269 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2270 adView = findViewById(R.id.adview);
2273 // `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:
2274 // https://code.google.com/p/android/issues/detail?id=20493#c8
2275 // ActivityCompat.invalidateOptionsMenu(this);
2279 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2280 // Store the `HitTestResult`.
2281 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2284 final String imageUrl;
2285 final String linkUrl;
2287 // Get a handle for the `ClipboardManager`.
2288 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2290 // Remove the lint errors below that `clipboardManager` might be `null`.
2291 assert clipboardManager != null;
2293 switch (hitTestResult.getType()) {
2294 // `SRC_ANCHOR_TYPE` is a link.
2295 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2296 // Get the target URL.
2297 linkUrl = hitTestResult.getExtra();
2299 // Set the target URL as the title of the `ContextMenu`.
2300 menu.setHeaderTitle(linkUrl);
2302 // Add a `Load URL` entry.
2303 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
2308 // Add a `Copy URL` entry.
2309 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2310 // Save the link URL in a `ClipData`.
2311 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2313 // Set the `ClipData` as the clipboard's primary clip.
2314 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2318 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2319 menu.add(R.string.cancel);
2322 case WebView.HitTestResult.EMAIL_TYPE:
2323 // Get the target URL.
2324 linkUrl = hitTestResult.getExtra();
2326 // Set the target URL as the title of the `ContextMenu`.
2327 menu.setHeaderTitle(linkUrl);
2329 // Add a `Write Email` entry.
2330 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2331 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2332 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2334 // Parse the url and set it as the data for the `Intent`.
2335 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2337 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2338 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2341 startActivity(emailIntent);
2345 // Add a `Copy Email Address` entry.
2346 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2347 // Save the email address in a `ClipData`.
2348 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2350 // Set the `ClipData` as the clipboard's primary clip.
2351 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2355 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2356 menu.add(R.string.cancel);
2359 // `IMAGE_TYPE` is an image.
2360 case WebView.HitTestResult.IMAGE_TYPE:
2361 // Get the image URL.
2362 imageUrl = hitTestResult.getExtra();
2364 // Set the image URL as the title of the `ContextMenu`.
2365 menu.setHeaderTitle(imageUrl);
2367 // Add a `View Image` entry.
2368 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2373 // Add a `Download Image` entry.
2374 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2375 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2376 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2377 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2379 // Store the image URL for use by `onRequestPermissionResult()`.
2380 downloadImageUrl = imageUrl;
2382 // Show a dialog if the user has previously denied the permission.
2383 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2384 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2385 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2387 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2388 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2389 } else { // Show the permission request directly.
2390 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2391 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2393 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2394 // Get a handle for the download image alert dialog.
2395 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2397 // Show the download image alert dialog.
2398 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2403 // Add a `Copy URL` entry.
2404 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2405 // Save the image URL in a `ClipData`.
2406 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2408 // Set the `ClipData` as the clipboard's primary clip.
2409 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2413 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2414 menu.add(R.string.cancel);
2418 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2419 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2420 // Get the image URL.
2421 imageUrl = hitTestResult.getExtra();
2423 // Set the image URL as the title of the `ContextMenu`.
2424 menu.setHeaderTitle(imageUrl);
2426 // Add a `View Image` entry.
2427 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2432 // Add a `Download Image` entry.
2433 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2434 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2435 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2436 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2438 // Store the image URL for use by `onRequestPermissionResult()`.
2439 downloadImageUrl = imageUrl;
2441 // Show a dialog if the user has previously denied the permission.
2442 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2443 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2444 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2446 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2447 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2448 } else { // Show the permission request directly.
2449 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2450 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2452 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2453 // Get a handle for the download image alert dialog.
2454 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2456 // Show the download image alert dialog.
2457 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2462 // Add a `Copy URL` entry.
2463 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2464 // Save the image URL in a `ClipData`.
2465 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2467 // Set the `ClipData` as the clipboard's primary clip.
2468 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2472 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2473 menu.add(R.string.cancel);
2479 public void onAddDomain(AppCompatDialogFragment dialogFragment) {
2480 // Reapply the domain settings on returning to `MainWebViewActivity`.
2481 reapplyDomainSettingsOnRestart = true;
2482 currentDomainName = "";
2484 // Get the new domain name `String` from `dialogFragment`.
2485 EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
2486 String domainNameString = domainNameEditText.getText().toString();
2488 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2489 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2490 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2492 // Create the domain and store the database ID in `currentDomainDatabaseId`.
2493 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
2495 // Create an intent to launch the domains activity.
2496 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2498 // Put extra information instructing the domains activity to directly load the current domain.
2499 domainsIntent.putExtra("LoadDomain", newDomainDatabaseId);
2502 startActivity(domainsIntent);
2506 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2507 // Get the `EditTexts` from the `dialogFragment`.
2508 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2509 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2511 // Extract the strings from the `EditTexts`.
2512 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2513 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2515 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2516 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2517 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2518 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2520 // Display the new bookmark below the current items in the (0 indexed) list.
2521 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2523 // Create the bookmark.
2524 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2526 // Update `bookmarksCursor` with the current contents of this folder.
2527 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2529 // Update the `ListView`.
2530 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2532 // Scroll to the new bookmark.
2533 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2537 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2538 // Get handles for the views in `dialogFragment`.
2539 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2540 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2541 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2543 // Get new folder name string.
2544 String folderNameString = createFolderNameEditText.getText().toString();
2546 // Get the new folder icon `Bitmap`.
2547 Bitmap folderIconBitmap;
2548 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2549 // Get the default folder icon and convert it to a `Bitmap`.
2550 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2551 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2552 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2553 } else { // Use the `WebView` favorite icon.
2554 folderIconBitmap = favoriteIconBitmap;
2557 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2558 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2559 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2560 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2562 // Move all the bookmarks down one in the display order.
2563 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2564 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2565 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2568 // Create the folder, which will be placed at the top of the `ListView`.
2569 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2571 // Update `bookmarksCursor` with the current contents of this folder.
2572 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2574 // Update the `ListView`.
2575 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2577 // Scroll to the new folder.
2578 bookmarksListView.setSelection(0);
2582 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2583 // Get the shortcut name.
2584 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2585 String shortcutNameString = shortcutNameEditText.getText().toString();
2587 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2588 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2590 // Setup the shortcut intent.
2591 Intent shortcutIntent = new Intent();
2592 shortcutIntent.setAction(Intent.ACTION_VIEW);
2593 shortcutIntent.setData(Uri.parse(formattedUrlString));
2595 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2596 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2598 // Add the required fields to the shortcut info builder.
2599 shortcutInfoBuilder.setIcon(favoriteIcon);
2600 shortcutInfoBuilder.setIntent(shortcutIntent);
2601 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2603 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2604 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2608 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2609 switch (downloadType) {
2610 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2611 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2612 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2615 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2616 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2617 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2623 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
2624 switch (requestCode) {
2625 case DOWNLOAD_FILE_REQUEST_CODE:
2626 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2627 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2629 // On API 23, displaying the fragment must be delayed or the app will crash.
2630 if (Build.VERSION.SDK_INT == 23) {
2631 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2633 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2636 // Reset the download variables.
2638 downloadContentDisposition = "";
2639 downloadContentLength = 0;
2642 case DOWNLOAD_IMAGE_REQUEST_CODE:
2643 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2644 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2646 // On API 23, displaying the fragment must be delayed or the app will crash.
2647 if (Build.VERSION.SDK_INT == 23) {
2648 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2650 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2653 // Reset the image URL variable.
2654 downloadImageUrl = "";
2660 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2661 // Download the image if it has an HTTP or HTTPS URI.
2662 if (imageUrl.startsWith("http")) {
2663 // Get a handle for the system `DOWNLOAD_SERVICE`.
2664 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2666 // Parse `imageUrl`.
2667 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2669 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2670 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2671 if (firstPartyCookiesEnabled) {
2672 // Get the cookies for `imageUrl`.
2673 String cookies = cookieManager.getCookie(imageUrl);
2675 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2676 downloadRequest.addRequestHeader("Cookie", cookies);
2679 // Get the file name from the dialog fragment.
2680 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2681 String imageName = downloadImageNameEditText.getText().toString();
2683 // Specify the download location.
2684 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2685 // Download to the public download directory.
2686 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2687 } else { // External write permission denied.
2688 // Download to the app's external download directory.
2689 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2692 // Allow `MediaScanner` to index the download if it is a media file.
2693 downloadRequest.allowScanningByMediaScanner();
2695 // Add the URL as the description for the download.
2696 downloadRequest.setDescription(imageUrl);
2698 // Show the download notification after the download is completed.
2699 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2701 // Remove the lint warning below that `downloadManager` might be `null`.
2702 assert downloadManager != null;
2704 // Initiate the download.
2705 downloadManager.enqueue(downloadRequest);
2706 } else { // The image is not an HTTP or HTTPS URI.
2707 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2712 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2713 // Download the file if it has an HTTP or HTTPS URI.
2714 if (downloadUrl.startsWith("http")) {
2715 // Get a handle for the system `DOWNLOAD_SERVICE`.
2716 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2718 // Parse `downloadUrl`.
2719 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2721 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2722 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2723 if (firstPartyCookiesEnabled) {
2724 // Get the cookies for `downloadUrl`.
2725 String cookies = cookieManager.getCookie(downloadUrl);
2727 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2728 downloadRequest.addRequestHeader("Cookie", cookies);
2731 // Get the file name from the dialog fragment.
2732 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2733 String fileName = downloadFileNameEditText.getText().toString();
2735 // Specify the download location.
2736 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2737 // Download to the public download directory.
2738 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2739 } else { // External write permission denied.
2740 // Download to the app's external download directory.
2741 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2744 // Allow `MediaScanner` to index the download if it is a media file.
2745 downloadRequest.allowScanningByMediaScanner();
2747 // Add the URL as the description for the download.
2748 downloadRequest.setDescription(downloadUrl);
2750 // Show the download notification after the download is completed.
2751 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2753 // Remove the lint warning below that `downloadManager` might be `null`.
2754 assert downloadManager != null;
2756 // Initiate the download.
2757 downloadManager.enqueue(downloadRequest);
2758 } else { // The download is not an HTTP or HTTPS URI.
2759 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2764 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2765 // Get handles for the views from `dialogFragment`.
2766 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2767 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2768 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2770 // Store the bookmark strings.
2771 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2772 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2774 // Update the bookmark.
2775 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2776 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2777 } else { // Update the bookmark using the `WebView` favorite icon.
2778 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2779 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2780 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2781 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2783 // Update the bookmark and the favorite icon.
2784 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2787 // Update `bookmarksCursor` with the current contents of this folder.
2788 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2790 // Update the `ListView`.
2791 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2795 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2796 // Get handles for the views from `dialogFragment`.
2797 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2798 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2799 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2800 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2802 // Get the new folder name.
2803 String newFolderNameString = editFolderNameEditText.getText().toString();
2805 // Check if the favorite icon has changed.
2806 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2807 // Update the name in the database.
2808 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2809 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2810 // Get the new folder icon `Bitmap`.
2811 Bitmap folderIconBitmap;
2812 if (defaultFolderIconRadioButton.isChecked()) {
2813 // Get the default folder icon and convert it to a `Bitmap`.
2814 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2815 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2816 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2817 } else { // Use the `WebView` favorite icon.
2818 folderIconBitmap = favoriteIconBitmap;
2821 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2822 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2823 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2824 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2826 // Update the folder icon in the database.
2827 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2828 } else { // The folder icon and the name have changed.
2829 // Get the new folder icon `Bitmap`.
2830 Bitmap folderIconBitmap;
2831 if (defaultFolderIconRadioButton.isChecked()) {
2832 // Get the default folder icon and convert it to a `Bitmap`.
2833 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2834 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2835 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2836 } else { // Use the `WebView` favorite icon.
2837 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2840 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2841 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2842 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2843 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2845 // Update the folder name and icon in the database.
2846 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2849 // Update `bookmarksCursor` with the current contents of this folder.
2850 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2852 // Update the `ListView`.
2853 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2857 public void onHttpAuthenticationCancel() {
2858 // Cancel the `HttpAuthHandler`.
2859 httpAuthHandler.cancel();
2863 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2864 // Get handles for the `EditTexts`.
2865 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2866 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2868 // Proceed with the HTTP authentication.
2869 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2872 public void viewSslCertificate(View view) {
2873 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2874 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2875 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2879 public void onSslErrorCancel() {
2880 sslErrorHandler.cancel();
2884 public void onSslErrorProceed() {
2885 sslErrorHandler.proceed();
2889 public void onSslMismatchBack() {
2890 if (mainWebView.canGoBack()) { // There is a back page in the history.
2891 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2892 navigatingHistory = true;
2895 mainWebView.goBack();
2896 } else { // There are no pages to go back to.
2897 // Load a blank page
2903 public void onSslMismatchProceed() {
2904 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2905 ignorePinnedSslCertificate = true;
2909 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2910 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2911 navigatingHistory = true;
2913 // Load the history entry.
2914 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2918 public void onClearHistory() {
2919 // Clear the history.
2920 mainWebView.clearHistory();
2923 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2925 public void onBackPressed() {
2926 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2927 // Close the navigation drawer.
2928 drawerLayout.closeDrawer(GravityCompat.START);
2929 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2930 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2931 // close the bookmarks drawer.
2932 drawerLayout.closeDrawer(GravityCompat.END);
2933 } else { // A subfolder is displayed.
2934 // Place the former parent folder in `currentFolder`.
2935 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2937 // Load the new folder.
2938 loadBookmarksFolder();
2941 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2942 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2943 navigatingHistory = true;
2946 mainWebView.goBack();
2947 } else { // There isn't anything to do in Privacy Browser.
2948 // Pass `onBackPressed()` to the system.
2949 super.onBackPressed();
2953 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2954 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2955 String unformattedUrlString = urlTextBox.getText().toString().trim();
2957 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2958 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2959 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2960 if (!unformattedUrlString.startsWith("http")) {
2961 unformattedUrlString = "http://" + unformattedUrlString;
2964 // Initialize `unformattedUrl`.
2965 URL unformattedUrl = null;
2967 // 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.
2969 unformattedUrl = new URL(unformattedUrlString);
2970 } catch (MalformedURLException e) {
2971 e.printStackTrace();
2974 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2975 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2976 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2977 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2978 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2979 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2982 Uri.Builder formattedUri = new Uri.Builder();
2983 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2985 // Decode `formattedUri` as a `String` in `UTF-8`.
2986 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2988 // Sanitize the search input and convert it to a search.
2989 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2991 // Add the base search URL.
2992 formattedUrlString = searchURL + encodedUrlString;
2995 // 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.
2996 urlTextBox.clearFocus();
2998 loadUrl(formattedUrlString);
3002 private void loadUrl(String url) {
3003 // Apply any custom domain settings.
3004 applyDomainSettings(url, true);
3007 mainWebView.loadUrl(url, customHeaders);
3009 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3010 urlIsLoading = true;
3013 public void findPreviousOnPage(View view) {
3014 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3015 mainWebView.findNext(false);
3018 public void findNextOnPage(View view) {
3019 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3020 mainWebView.findNext(true);
3023 public void closeFindOnPage(View view) {
3024 // Delete the contents of `find_on_page_edittext`.
3025 findOnPageEditText.setText(null);
3027 // Clear the highlighted phrases.
3028 mainWebView.clearMatches();
3030 // Hide the Find on Page `RelativeLayout`.
3031 findOnPageLinearLayout.setVisibility(View.GONE);
3033 // Show the URL app bar.
3034 supportAppBar.setVisibility(View.VISIBLE);
3036 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3037 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3040 private void applyAppSettings() {
3041 // Get a handle for the shared preferences.
3042 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3044 // Store the values from the shared preferences in variables.
3045 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3046 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3047 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3048 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3049 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3050 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3051 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3052 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3053 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3054 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3055 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3056 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3057 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
3058 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3060 // Set the homepage, search, and proxy options.
3061 if (proxyThroughOrbot) { // Set the Tor options.
3062 // Set `torHomepageString` as `homepage`.
3063 homepage = torHomepageString;
3065 // If formattedUrlString is null assign the homepage to it.
3066 if (formattedUrlString == null) {
3067 formattedUrlString = homepage;
3070 // Set the search URL.
3071 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3072 searchURL = torSearchCustomURLString;
3073 } else { // Use the string from the pre-built list.
3074 searchURL = torSearchString;
3077 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3078 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3080 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3082 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3084 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3087 // Display a message to the user if we are waiting on Orbot.
3088 if (!orbotStatus.equals("ON")) {
3089 // Set `waitingForOrbot`.
3090 waitingForOrbot = true;
3092 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3093 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3095 } else { // Set the non-Tor options.
3096 // Set `homepageString` as `homepage`.
3097 homepage = homepageString;
3099 // If formattedUrlString is null assign the homepage to it.
3100 if (formattedUrlString == null) {
3101 formattedUrlString = homepage;
3104 // Set the search URL.
3105 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3106 searchURL = searchCustomURLString;
3107 } else { // Use the string from the pre-built list.
3108 searchURL = searchString;
3111 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3112 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3114 // Set the default `appBar` background. `this` refers to the context.
3116 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3118 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3121 // Reset `waitingForOrbot.
3122 waitingForOrbot = false;
3125 // Set swipe to refresh.
3126 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
3128 // Set Do Not Track status.
3129 if (doNotTrackEnabled) {
3130 customHeaders.put("DNT", "1");
3132 customHeaders.remove("DNT");
3135 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3136 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3137 if (hideSystemBarsOnFullscreen) { // Hide everything.
3138 // Remove the translucent navigation setting if it is currently flagged.
3139 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3141 // Remove the translucent status bar overlay.
3142 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3144 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3145 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3147 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3148 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3149 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3151 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3152 } else { // Hide everything except the status and navigation bars.
3153 // Add the translucent status flag if it is unset.
3154 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3156 if (translucentNavigationBarOnFullscreen) {
3157 // Set the navigation bar to be translucent.
3158 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3160 // Set the navigation bar to be black.
3161 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3164 } else { // Switch to normal viewing mode.
3165 // Reset `inFullScreenBrowsingMode` to `false`.
3166 inFullScreenBrowsingMode = false;
3168 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3169 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3173 // Show the `BannerAd` in the free flavor.
3174 if (BuildConfig.FLAVOR.contentEquals("free")) {
3175 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
3176 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
3178 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3179 adView = findViewById(R.id.adview);
3182 // Remove the translucent navigation bar flag if it is set.
3183 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3185 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3186 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3188 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3189 rootCoordinatorLayout.setSystemUiVisibility(0);
3191 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3192 rootCoordinatorLayout.setFitsSystemWindows(true);
3197 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3198 @SuppressWarnings("deprecation")
3199 private void applyDomainSettings(String url, boolean resetFavoriteIcon) {
3200 // Reset `navigatingHistory`.
3201 navigatingHistory = false;
3203 // Parse the URL into a URI.
3204 Uri uri = Uri.parse(url);
3206 // Extract the domain from `uri`.
3207 String hostName = uri.getHost();
3209 // Initialize `loadingNewDomainName`.
3210 boolean loadingNewDomainName;
3212 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3213 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3214 //noinspection SimplifiableIfStatement
3215 if ((hostName == null) || (currentDomainName == null)) {
3216 loadingNewDomainName = true;
3217 } else { // Determine if `hostName` equals `currentDomainName`.
3218 loadingNewDomainName = !hostName.equals(currentDomainName);
3221 // 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.
3222 if (loadingNewDomainName) {
3223 // Set the new `hostname` as the `currentDomainName`.
3224 currentDomainName = hostName;
3226 // Reset `ignorePinnedSslCertificate`.
3227 ignorePinnedSslCertificate = false;
3229 // Reset the favorite icon if specified.
3230 if (resetFavoriteIcon) {
3231 favoriteIconBitmap = favoriteIconDefaultBitmap;
3232 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3235 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3236 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3237 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3239 // Get a full cursor from `domainsDatabaseHelper`.
3240 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3242 // Initialize `domainSettingsSet`.
3243 Set<String> domainSettingsSet = new HashSet<>();
3245 // Get the domain name column index.
3246 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3248 // Populate `domainSettingsSet`.
3249 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3250 // Move `domainsCursor` to the current row.
3251 domainNameCursor.moveToPosition(i);
3253 // Store the domain name in `domainSettingsSet`.
3254 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3257 // Close `domainNameCursor.
3258 domainNameCursor.close();
3260 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3261 domainSettingsApplied = false;
3262 String domainNameInDatabase = null;
3264 // Check the hostname.
3265 if (domainSettingsSet.contains(hostName)) {
3266 domainSettingsApplied = true;
3267 domainNameInDatabase = hostName;
3270 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3271 if (hostName != null) {
3272 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3273 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3274 domainSettingsApplied = true;
3275 domainNameInDatabase = "*." + hostName;
3278 // Strip out the lowest subdomain of `host`.
3279 hostName = hostName.substring(hostName.indexOf(".") + 1);
3283 // Get a handle for the shared preference. `this` references the current context.
3284 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3286 // Store the general preference information.
3287 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3288 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3289 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3290 nightMode = sharedPreferences.getBoolean("night_mode", false);
3292 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3293 // Get a cursor for the current host and move it to the first position.
3294 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3295 currentHostDomainSettingsCursor.moveToFirst();
3297 // Get the settings from the cursor.
3298 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3299 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3300 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3301 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3302 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3303 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3304 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3305 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3306 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3307 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3308 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3309 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3310 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3311 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3312 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3313 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3314 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3315 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3316 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3317 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3318 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3320 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3321 switch (nightModeInt) {
3322 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3326 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3331 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3333 javaScriptEnabled = true;
3336 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3337 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3338 pinnedDomainSslStartDate = null;
3340 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3343 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3344 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3345 pinnedDomainSslEndDate = null;
3347 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3350 // Close `currentHostDomainSettingsCursor`.
3351 currentHostDomainSettingsCursor.close();
3353 // Apply the domain settings.
3354 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3355 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3356 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3357 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3359 // Apply the font size.
3360 if (fontSize == 0) { // Apply the default font size.
3361 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3362 } else { // Apply the specified font size.
3363 mainWebView.getSettings().setTextZoom(fontSize);
3366 // Set third-party cookies status if API >= 21.
3367 if (Build.VERSION.SDK_INT >= 21) {
3368 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3371 // 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.
3372 // <https://redmine.stoutner.com/issues/160>
3373 if (!urlIsLoading) {
3374 switch (userAgentString) {
3375 case "System default user agent":
3376 // Set the user agent according to the system default.
3377 switch (defaultUserAgentString) {
3378 case "WebView default user agent":
3379 // Set the user agent to `""`, which uses the default value.
3380 mainWebView.getSettings().setUserAgentString("");
3383 case "Custom user agent":
3384 // Set the custom user agent.
3385 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3389 // Use the selected user agent.
3390 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3394 case "WebView default user agent":
3395 // Set the user agent to `""`, which uses the default value.
3396 mainWebView.getSettings().setUserAgentString("");
3400 // Use the selected user agent.
3401 mainWebView.getSettings().setUserAgentString(userAgentString);
3404 // Store the applied user agent string.
3405 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3408 // 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.
3410 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3412 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3414 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3415 // Store the values from `sharedPreferences` in variables.
3416 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3417 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3418 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3419 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3420 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3421 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3422 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3423 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3424 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3426 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3428 javaScriptEnabled = true;
3431 // Apply the default settings.
3432 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3433 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3434 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3435 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3436 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3438 // Reset the pinned SSL certificate information.
3439 domainSettingsDatabaseId = -1;
3440 pinnedDomainSslCertificate = false;
3441 pinnedDomainSslIssuedToCNameString = "";
3442 pinnedDomainSslIssuedToONameString = "";
3443 pinnedDomainSslIssuedToUNameString = "";
3444 pinnedDomainSslIssuedByCNameString = "";
3445 pinnedDomainSslIssuedByONameString = "";
3446 pinnedDomainSslIssuedByUNameString = "";
3447 pinnedDomainSslStartDate = null;
3448 pinnedDomainSslEndDate = null;
3450 // Set third-party cookies status if API >= 21.
3451 if (Build.VERSION.SDK_INT >= 21) {
3452 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3455 // 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.
3456 // <https://redmine.stoutner.com/issues/160>
3457 if (!urlIsLoading) {
3458 switch (defaultUserAgentString) {
3459 case "WebView default user agent":
3460 // Set the user agent to `""`, which uses the default value.
3461 mainWebView.getSettings().setUserAgentString("");
3464 case "Custom user agent":
3465 // Set the custom user agent.
3466 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3470 // Use the selected user agent.
3471 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3474 // Store the applied user agent string.
3475 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3478 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3479 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3482 // Close `domainsDatabaseHelper`.
3483 domainsDatabaseHelper.close();
3485 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3486 onTheFlyDisplayImagesSet = false;
3487 setDisplayWebpageImages();
3489 // Update the privacy icons, but only if `mainMenu` has already been populated.
3490 if (mainMenu != null) {
3491 updatePrivacyIcons(true);
3496 private void setDisplayWebpageImages() {
3497 if (!onTheFlyDisplayImagesSet) {
3498 if (domainSettingsApplied) { // Custom domain settings are applied.
3499 switch (displayWebpageImagesInt) {
3500 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3501 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3504 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3505 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3508 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3509 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3512 } else { // Default settings are applied.
3513 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3518 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3519 // Get handles for the icons.
3520 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3521 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3522 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3523 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3525 // Update `privacyIcon`.
3526 if (javaScriptEnabled) { // JavaScript is enabled.
3527 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3528 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3529 privacyIconMenuItem.setIcon(R.drawable.warning);
3530 } else { // All the dangerous features are disabled.
3531 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3534 // Update `firstPartyCookiesIcon`.
3535 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3536 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3537 } else { // First-party cookies are disabled.
3539 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3541 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3545 // Update `domStorageIcon`.
3546 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3547 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3548 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3550 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3552 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3554 } else { // JavaScript is disabled, so DOM storage is ghosted.
3556 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3558 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3562 // Update `formDataIcon`.
3563 if (saveFormDataEnabled) { // Form data is enabled.
3564 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3565 } else { // Form data is disabled.
3567 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3569 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3573 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3574 if (runInvalidateOptionsMenu) {
3575 invalidateOptionsMenu();
3579 private void highlightUrlText() {
3580 String urlString = urlTextBox.getText().toString();
3582 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3583 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3584 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3585 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3588 // Get the index of the `/` immediately after the domain name.
3589 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3591 // De-emphasize the text after the domain name.
3592 if (endOfDomainName > 0) {
3593 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3597 private void loadBookmarksFolder() {
3598 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3599 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3601 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3602 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3604 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3605 // Inflate the individual item layout. `false` does not attach it to the root.
3606 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3610 public void bindView(View view, Context context, Cursor cursor) {
3611 // Get handles for the views.
3612 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3613 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3615 // Get the favorite icon byte array from the `Cursor`.
3616 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3618 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3619 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3621 // Display the bitmap in `bookmarkFavoriteIcon`.
3622 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3624 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3625 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3626 bookmarkNameTextView.setText(bookmarkNameString);
3628 // Make the font bold for folders.
3629 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3630 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3631 } else { // Reset the font to default for normal bookmarks.
3632 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3637 // Populate the `ListView` with the adapter.
3638 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3640 // Set the bookmarks drawer title.
3641 if (currentBookmarksFolder.isEmpty()) {
3642 bookmarksTitleTextView.setText(R.string.bookmarks);
3644 bookmarksTitleTextView.setText(currentBookmarksFolder);