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.CreateBookmarkDialog;
113 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
114 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
115 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
116 import com.stoutner.privacybrowser.dialogs.DownloadLocationPermissionDialog;
117 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
118 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
119 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
120 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
121 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
122 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
123 import com.stoutner.privacybrowser.helpers.BlockListHelper;
124 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
125 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
126 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
127 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
128 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
130 import java.io.ByteArrayInputStream;
131 import java.io.ByteArrayOutputStream;
133 import java.io.IOException;
134 import java.io.UnsupportedEncodingException;
135 import java.net.MalformedURLException;
137 import java.net.URLDecoder;
138 import java.net.URLEncoder;
139 import java.util.ArrayList;
140 import java.util.Date;
141 import java.util.HashMap;
142 import java.util.HashSet;
143 import java.util.List;
144 import java.util.Map;
145 import java.util.Set;
147 // AppCompatActivity from android.support.v7.app.AppCompatActivity must be used to have access to the SupportActionBar until the minimum API is >= 21.
148 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener,
149 CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener,
150 DownloadLocationPermissionDialog.DownloadLocationPermissionDialogListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener,
151 HttpAuthenticationDialog.HttpAuthenticationListener, NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener,
152 SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
154 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`,
155 // `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
156 // `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`,
157 // and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
158 public static boolean darkTheme;
160 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
161 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
162 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
163 public static Bitmap favoriteIconBitmap;
165 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
166 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
167 public static String formattedUrlString;
169 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
170 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
171 public static SslCertificate sslCertificate;
173 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
174 public static String orbotStatus;
176 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
177 public static String webViewTitle;
179 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
180 public static String appliedUserAgentString;
182 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
183 public static boolean reloadOnRestart;
185 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
186 public static boolean loadUrlOnRestart;
188 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
189 public static boolean restartFromBookmarksActivity;
191 // The block list versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
192 public static String easyListVersion;
193 public static String easyPrivacyVersion;
194 public static String fanboyAnnoyanceVersion;
195 public static String fanboySocialVersion;
197 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
198 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
199 public static String currentBookmarksFolder;
201 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
202 public static int domainSettingsDatabaseId;
204 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
205 public static String pinnedDomainSslIssuedToCNameString;
206 public static String pinnedDomainSslIssuedToONameString;
207 public static String pinnedDomainSslIssuedToUNameString;
208 public static String pinnedDomainSslIssuedByCNameString;
209 public static String pinnedDomainSslIssuedByONameString;
210 public static String pinnedDomainSslIssuedByUNameString;
211 public static Date pinnedDomainSslStartDate;
212 public static Date pinnedDomainSslEndDate;
215 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
216 private ActionBar appBar;
218 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
219 private boolean navigatingHistory;
221 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
222 private Bitmap favoriteIconDefaultBitmap;
224 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
225 private DrawerLayout drawerLayout;
227 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
228 private CoordinatorLayout rootCoordinatorLayout;
230 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
231 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
232 private WebView mainWebView;
234 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
235 private FrameLayout fullScreenVideoFrameLayout;
237 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
238 private SwipeRefreshLayout swipeRefreshLayout;
240 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
241 private RelativeLayout urlAppBarRelativeLayout;
243 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
244 private ImageView favoriteIconImageView;
246 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
247 private CookieManager cookieManager;
249 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
250 private final Map<String, String> customHeaders = new HashMap<>();
252 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
253 private boolean javaScriptEnabled;
255 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
256 private boolean firstPartyCookiesEnabled;
258 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
259 private boolean thirdPartyCookiesEnabled;
261 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
262 private boolean domStorageEnabled;
264 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
265 private boolean saveFormDataEnabled;
267 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
268 private boolean nightMode;
270 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
271 private boolean swipeToRefreshEnabled;
273 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
274 private boolean displayWebpageImagesBoolean;
276 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
277 private String homepage;
279 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
280 private String searchURL;
282 // The block list variables are used in `onCreate()` and `applyAppSettings()`.
283 private boolean easyListEnabled;
284 private boolean easyPrivacyEnabled;
285 private boolean fanboysAnnoyanceListEnabled;
286 private boolean fanboysSocialBlockingListEnabled;
288 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
289 private Runtime privacyBrowserRuntime;
291 // `proxyThroughOrbot` is used in `onRestart()` and `applyAppSettings()`.
292 boolean proxyThroughOrbot;
294 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
295 private boolean incognitoModeEnabled;
297 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
298 private boolean fullScreenBrowsingModeEnabled;
300 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
301 private boolean inFullScreenBrowsingMode;
303 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
304 private boolean hideSystemBarsOnFullscreen;
306 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
307 private boolean translucentNavigationBarOnFullscreen;
309 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
310 private boolean reapplyDomainSettingsOnRestart;
312 // `reapplyAppSettingsOnRestart` is used in `onNavigationItemSelected()` and `onRestart()`.
313 private boolean reapplyAppSettingsOnRestart;
315 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
316 private String currentDomainName;
318 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
319 private boolean ignorePinnedSslCertificate;
321 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
322 private boolean waitingForOrbot;
324 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
325 private boolean domainSettingsApplied;
327 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
328 private int displayWebpageImagesInt;
330 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
331 private boolean onTheFlyDisplayImagesSet;
333 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
334 private String waitingForOrbotHTMLString;
336 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
337 private String privateDataDirectoryString;
339 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
340 private LinearLayout findOnPageLinearLayout;
342 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
343 private EditText findOnPageEditText;
345 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
346 private Menu mainMenu;
348 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
349 private ActionBarDrawerToggle drawerToggle;
351 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
352 private Toolbar supportAppBar;
354 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
355 private EditText urlTextBox;
357 // The color spans are used in `onCreate()` and `highlightUrlText()`.
358 private ForegroundColorSpan redColorSpan;
359 private ForegroundColorSpan initialGrayColorSpan;
360 private ForegroundColorSpan finalGrayColorSpan;
362 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
365 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
366 private SslErrorHandler sslErrorHandler;
368 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
369 private static HttpAuthHandler httpAuthHandler;
371 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
372 private InputMethodManager inputMethodManager;
374 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
375 private RelativeLayout mainWebViewRelativeLayout;
377 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
378 private boolean urlIsLoading;
380 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
381 private boolean pinnedDomainSslCertificate;
383 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
384 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
386 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
387 private ListView bookmarksListView;
389 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
390 private TextView bookmarksTitleTextView;
392 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
393 private Cursor bookmarksCursor;
395 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
396 private CursorAdapter bookmarksCursorAdapter;
398 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
399 private String oldFolderNameString;
401 // The download strings are used in `onCreate()` and `onRequestPermissionResult()`.
402 private String downloadUrl;
403 private String downloadContentDisposition;
404 private long downloadContentLength;
406 // `downloadImageUrl` is used in `onCreateContextMenu()` and `onRequestPermissionResult()`.
407 private String downloadImageUrl;
409 // The request codes are used in `onCreate()`, `onCreateContextMenu()`, `onCloseDownloadLocationPermissionDialog()`, and `onRequestPermissionResult()`.
410 private final int DOWNLOAD_FILE_REQUEST_CODE = 1;
411 private final int DOWNLOAD_IMAGE_REQUEST_CODE = 2;
414 // 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.
415 // Also, remove the warning about needing to override `performClick()` when using an `OnTouchListener` with `WebView`.
416 @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
417 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
418 @SuppressWarnings("deprecation")
419 protected void onCreate(Bundle savedInstanceState) {
420 // Get a handle for `sharedPreferences`. `this` references the current context.
421 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
423 // Get the theme preference.
424 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
426 // Set the activity theme.
428 setTheme(R.style.PrivacyBrowserDark);
430 setTheme(R.style.PrivacyBrowserLight);
433 // Run the default commands.
434 super.onCreate(savedInstanceState);
436 // Set the content view.
437 setContentView(R.layout.main_drawerlayout);
439 // Get a handle for `inputMethodManager`.
440 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
442 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
443 supportAppBar = findViewById(R.id.app_bar);
444 setSupportActionBar(supportAppBar);
445 appBar = getSupportActionBar();
447 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
448 assert appBar != null;
450 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
451 appBar.setCustomView(R.layout.url_app_bar);
452 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
454 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
455 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
456 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
457 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
459 // Get a handle for `urlTextBox`.
460 urlTextBox = findViewById(R.id.url_edittext);
462 // Remove the formatting from `urlTextBar` when the user is editing the text.
463 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
464 if (hasFocus) { // The user is editing `urlTextBox`.
465 // Remove the highlighting.
466 urlTextBox.getText().removeSpan(redColorSpan);
467 urlTextBox.getText().removeSpan(initialGrayColorSpan);
468 urlTextBox.getText().removeSpan(finalGrayColorSpan);
469 } else { // The user has stopped editing `urlTextBox`.
470 // Reapply the highlighting.
475 // Set the go button on the keyboard to load the URL in `urlTextBox`.
476 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
477 // If the event is a key-down event on the `enter` button, load the URL.
478 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
479 // Load the URL into the mainWebView and consume the event.
481 loadUrlFromTextBox();
482 } catch (UnsupportedEncodingException e) {
485 // If the enter key was pressed, consume the event.
488 // If any other key was pressed, do not consume the event.
493 // Set `waitingForOrbotHTMLString`.
494 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
496 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
497 currentDomainName = "";
498 orbotStatus = "unknown";
499 waitingForOrbot = false;
501 // Create an Orbot status `BroadcastReceiver`.
502 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
504 public void onReceive(Context context, Intent intent) {
505 // Store the content of the status message in `orbotStatus`.
506 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
508 // If we are waiting on Orbot, load the website now that Orbot is connected.
509 if (orbotStatus.equals("ON") && waitingForOrbot) {
510 // Reset `waitingForOrbot`.
511 waitingForOrbot = false;
513 // Load `formattedUrlString
514 loadUrl(formattedUrlString);
519 // Register `orbotStatusBroadcastReceiver` on `this` context.
520 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
522 // Get handles for views that need to be accessed.
523 drawerLayout = findViewById(R.id.drawerlayout);
524 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
525 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
526 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
527 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
528 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
529 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
530 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
531 mainWebView = findViewById(R.id.main_webview);
532 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
533 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
534 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
535 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
536 favoriteIconImageView = findViewById(R.id.favorite_icon);
538 // 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.
540 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
541 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
542 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
543 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
545 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
546 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
547 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
548 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
551 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
552 launchBookmarksActivityFab.setOnClickListener(v -> {
553 // Create an intent to launch the bookmarks activity.
554 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
556 // Include the current folder with the `Intent`.
557 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
560 startActivity(bookmarksIntent);
563 // Set the create new bookmark folder FAB to display the `AlertDialog`.
564 createBookmarkFolderFab.setOnClickListener(v -> {
565 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
566 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
567 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
570 // Set the create new bookmark FAB to display the `AlertDialog`.
571 createBookmarkFab.setOnClickListener(view -> {
572 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
573 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
574 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
577 // Create a double-tap listener to toggle full-screen mode.
578 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
579 // Override `onDoubleTap()`. All other events are handled using the default settings.
581 public boolean onDoubleTap(MotionEvent event) {
582 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
583 // Toggle `inFullScreenBrowsingMode`.
584 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
586 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
587 // Hide the `appBar`.
590 // Hide the `BannerAd` in the free flavor.
591 if (BuildConfig.FLAVOR.contentEquals("free")) {
592 BannerAd.hideAd(adView);
595 // Modify the system bars.
596 if (hideSystemBarsOnFullscreen) { // Hide everything.
597 // Remove the translucent overlays.
598 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
600 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
601 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
603 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
604 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
605 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
607 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
609 // Set `rootCoordinatorLayout` to fill the whole screen.
610 rootCoordinatorLayout.setFitsSystemWindows(false);
611 } else { // Hide everything except the status and navigation bars.
612 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
613 rootCoordinatorLayout.setFitsSystemWindows(false);
615 // 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.
616 if (translucentNavigationBarOnFullscreen) {
617 // Set the navigation bar to be translucent.
618 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
621 } else { // Switch to normal viewing mode.
622 // Show the `appBar`.
625 // Show the `BannerAd` in the free flavor.
626 if (BuildConfig.FLAVOR.contentEquals("free")) {
627 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
628 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
630 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
631 adView = findViewById(R.id.adview);
634 // Remove the translucent navigation bar flag if it is set.
635 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
637 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
638 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
640 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
641 rootCoordinatorLayout.setSystemUiVisibility(0);
643 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
644 rootCoordinatorLayout.setFitsSystemWindows(true);
647 // Consume the double-tap.
649 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
655 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
656 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
657 // Call `performClick()` on the view, which is required for accessibility.
660 // Send the `event` to `gestureDetector`.
661 return gestureDetector.onTouchEvent(event);
664 // Update `findOnPageCountTextView`.
665 mainWebView.setFindListener(new WebView.FindListener() {
666 // Get a handle for `findOnPageCountTextView`.
667 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
670 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
671 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
672 // Set `findOnPageCountTextView` to `0/0`.
673 findOnPageCountTextView.setText(R.string.zero_of_zero);
674 } else if (isDoneCounting) { // There are matches.
675 // `activeMatchOrdinal` is zero-based.
676 int activeMatch = activeMatchOrdinal + 1;
678 // Build the match string.
679 String matchString = activeMatch + "/" + numberOfMatches;
681 // Set `findOnPageCountTextView`.
682 findOnPageCountTextView.setText(matchString);
687 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
688 findOnPageEditText.addTextChangedListener(new TextWatcher() {
690 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
695 public void onTextChanged(CharSequence s, int start, int before, int count) {
700 public void afterTextChanged(Editable s) {
701 // Search for the text in `mainWebView`.
702 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
706 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
707 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
708 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
709 // Hide the soft keyboard. `0` indicates no additional flags.
710 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
712 // Consume the event.
714 } else { // A different key was pressed.
715 // Do not consume the event.
720 // Implement swipe to refresh
721 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
722 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
723 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
725 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
726 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
727 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
729 // Listen for touches on the navigation menu.
730 final NavigationView navigationView = findViewById(R.id.navigationview);
731 navigationView.setNavigationItemSelectedListener(this);
733 // 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.
734 final Menu navigationMenu = navigationView.getMenu();
735 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
736 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
737 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
739 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
740 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
741 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
743 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
744 currentBookmarksFolder = "";
746 // Load the home folder, which is `""` in the database.
747 loadBookmarksFolder();
749 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
750 // Convert the id from long to int to match the format of the bookmarks database.
751 int databaseID = (int) id;
753 // Get the bookmark `Cursor` for this ID and move it to the first row.
754 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
755 bookmarkCursor.moveToFirst();
757 // Act upon the bookmark according to the type.
758 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
759 // Store the new folder name in `currentBookmarksFolder`.
760 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
762 // Load the new folder.
763 loadBookmarksFolder();
764 } else { // The selected bookmark is not a folder.
765 // Load the bookmark URL.
766 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
768 // Close the bookmarks drawer.
769 drawerLayout.closeDrawer(GravityCompat.END);
772 // Close the `Cursor`.
773 bookmarkCursor.close();
776 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
777 // Convert the database ID from `long` to `int`.
778 int databaseId = (int) id;
780 // Find out if the selected bookmark is a folder.
781 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
784 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
785 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
787 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
788 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
789 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
791 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
792 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
793 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
796 // Consume the event.
800 // The `DrawerListener` allows us to update the Navigation Menu.
801 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
803 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
807 public void onDrawerOpened(@NonNull View drawerView) {
811 public void onDrawerClosed(@NonNull View drawerView) {
815 public void onDrawerStateChanged(int newState) {
816 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
817 // Update the `Back`, `Forward`, and `History` menu items.
818 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
819 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
820 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
822 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
823 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
825 // Clear the focus from `urlTextBox` if it has it.
826 urlTextBox.clearFocus();
831 // drawerToggle creates the hamburger icon at the start of the AppBar.
832 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
834 // Get a handle for the progress bar.
835 final ProgressBar progressBar = findViewById(R.id.progress_bar);
837 mainWebView.setWebChromeClient(new WebChromeClient() {
838 // Update the progress bar when a page is loading.
840 public void onProgressChanged(WebView view, int progress) {
841 // Inject the night mode CSS if night mode is enabled.
843 // `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
844 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
845 // `border: none` removes all borders, which can also be used to underline text.
846 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
847 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
848 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
849 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
850 // Initialize a `Handler` to display `mainWebView`.
851 Handler displayWebViewHandler = new Handler();
853 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
854 Runnable displayWebViewRunnable = () -> {
855 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
856 if (progressBar.getVisibility() == View.GONE) {
857 mainWebView.setVisibility(View.VISIBLE);
861 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
862 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
866 // Update the progress bar.
867 progressBar.setProgress(progress);
869 // Set the visibility of the progress bar.
870 if (progress < 100) {
871 // Show the progress bar.
872 progressBar.setVisibility(View.VISIBLE);
874 // Hide the progress bar.
875 progressBar.setVisibility(View.GONE);
877 // Display `mainWebView` if night mode is disabled.
878 // 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
879 // currently enabled.
881 mainWebView.setVisibility(View.VISIBLE);
884 //Stop the `SwipeToRefresh` indicator if it is running
885 swipeRefreshLayout.setRefreshing(false);
889 // Set the favorite icon when it changes.
891 public void onReceivedIcon(WebView view, Bitmap icon) {
892 // Only update the favorite icon if the website has finished loading.
893 if (progressBar.getVisibility() == View.GONE) {
894 // Save a copy of the favorite icon.
895 favoriteIconBitmap = icon;
897 // Place the favorite icon in the appBar.
898 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
902 // Save a copy of the title when it changes.
904 public void onReceivedTitle(WebView view, String title) {
905 // Save a copy of the title.
906 webViewTitle = title;
909 // Enter full screen video
911 public void onShowCustomView(View view, CustomViewCallback callback) {
912 // Pause the ad if this is the free flavor.
913 if (BuildConfig.FLAVOR.contentEquals("free")) {
914 BannerAd.pauseAd(adView);
917 // Remove the translucent overlays.
918 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
920 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
921 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
923 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
924 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
925 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
927 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
929 // Set `rootCoordinatorLayout` to fill the entire screen.
930 rootCoordinatorLayout.setFitsSystemWindows(false);
932 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
933 fullScreenVideoFrameLayout.addView(view);
934 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
937 // Exit full screen video
938 public void onHideCustomView() {
939 // Hide `fullScreenVideoFrameLayout`.
940 fullScreenVideoFrameLayout.removeAllViews();
941 fullScreenVideoFrameLayout.setVisibility(View.GONE);
943 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
944 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
946 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
947 rootCoordinatorLayout.setFitsSystemWindows(true);
949 // Show the ad if this is the free flavor.
950 if (BuildConfig.FLAVOR.contentEquals("free")) {
951 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
952 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
954 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
955 adView = findViewById(R.id.adview);
960 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
961 registerForContextMenu(mainWebView);
963 // Allow the downloading of files.
964 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
965 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
966 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
967 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
969 // Store the variables for future use by `onRequestPermissionsResult()`.
971 downloadContentDisposition = contentDisposition;
972 downloadContentLength = contentLength;
974 // Show a dialog if the user has previously denied the permission.
975 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
976 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_FILE.
977 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_FILE);
979 // Show the download location permission alert dialog. The permission will be requested when the the dialog is closed.
980 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
981 } else { // Show the permission request directly.
982 // Request the permission. The download dialog will be launched by `onRequestPermissionResult()`.
983 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
985 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
986 // Get a handle for the download file alert dialog.
987 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
989 // Show the download file alert dialog.
990 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
994 // Allow pinch to zoom.
995 mainWebView.getSettings().setBuiltInZoomControls(true);
997 // Hide zoom controls.
998 mainWebView.getSettings().setDisplayZoomControls(false);
1000 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1001 mainWebView.getSettings().setUseWideViewPort(true);
1003 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1004 mainWebView.getSettings().setLoadWithOverviewMode(true);
1006 // Explicitly disable geolocation.
1007 mainWebView.getSettings().setGeolocationEnabled(false);
1009 // Initialize cookieManager.
1010 cookieManager = CookieManager.getInstance();
1012 // 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).
1013 customHeaders.put("X-Requested-With", "");
1015 // 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.
1016 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1018 // Get the intent that started the app.
1019 final Intent launchingIntent = getIntent();
1021 // Extract the launching intent data as `launchingIntentUriData`.
1022 final Uri launchingIntentUriData = launchingIntent.getData();
1024 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1025 if (launchingIntentUriData != null) {
1026 formattedUrlString = launchingIntentUriData.toString();
1029 // Get a handle for the `Runtime`.
1030 privacyBrowserRuntime = Runtime.getRuntime();
1032 // Store the application's private data directory.
1033 privateDataDirectoryString = getApplicationInfo().dataDir;
1034 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1036 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1037 inFullScreenBrowsingMode = false;
1039 // Initialize AdView for the free flavor.
1040 adView = findViewById(R.id.adview);
1042 // Initialize the privacy settings variables.
1043 javaScriptEnabled = false;
1044 firstPartyCookiesEnabled = false;
1045 thirdPartyCookiesEnabled = false;
1046 domStorageEnabled = false;
1047 saveFormDataEnabled = false;
1050 // Initialize `webViewTitle`.
1051 webViewTitle = getString(R.string.no_title);
1053 // Initialize `favoriteIconBitmap`. `ContextCompat` must be used until API >= 21.
1054 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1055 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1056 assert favoriteIconBitmapDrawable != null;
1057 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1059 // If the favorite icon is null, load the default.
1060 if (favoriteIconBitmap == null) {
1061 favoriteIconBitmap = favoriteIconDefaultBitmap;
1064 // Apply the app settings from the shared preferences.
1067 // Instantiate the block list helper.
1068 BlockListHelper blockListHelper = new BlockListHelper();
1070 // Parse the block lists.
1071 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
1072 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
1073 final ArrayList<List<String[]>> fanboyAnnoyance = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
1074 final ArrayList<List<String[]>> fanboySocial = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
1076 // Store the list versions.
1077 easyListVersion = easyList.get(0).get(0)[0];
1078 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
1079 fanboyAnnoyanceVersion = fanboyAnnoyance.get(0).get(0)[0];
1080 fanboySocialVersion = fanboySocial.get(0).get(0)[0];
1082 mainWebView.setWebViewClient(new WebViewClient() {
1083 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1084 // The deprecated `shouldOverrideUrlLoading` must be used until API >= 24.
1085 @SuppressWarnings("deprecation")
1087 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1088 if (url.startsWith("http")) { // Load the URL in Privacy Browser.
1089 // Apply the domain settings for the new URL.
1090 applyDomainSettings(url, true);
1092 // Returning false causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
1094 } else if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1095 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1096 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1098 // Parse the url and set it as the data for the intent.
1099 emailIntent.setData(Uri.parse(url));
1101 // Open the email program in a new task instead of as part of Privacy Browser.
1102 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1105 startActivity(emailIntent);
1107 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1109 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1110 // Open the dialer and load the phone number, but wait for the user to place the call.
1111 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1113 // Add the phone number to the intent.
1114 dialIntent.setData(Uri.parse(url));
1116 // Open the dialer in a new task instead of as part of Privacy Browser.
1117 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1120 startActivity(dialIntent);
1122 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1124 } else { // Load a system chooser to select an app that can handle the URL.
1125 // Open an app that can handle the URL.
1126 Intent genericIntent = new Intent(Intent.ACTION_VIEW);
1128 // Add the URL to the intent.
1129 genericIntent.setData(Uri.parse(url));
1131 // List all apps that can handle the URL instead of just opening the first one.
1132 genericIntent.addCategory(Intent.CATEGORY_BROWSABLE);
1134 // Open the app in a new task instead of as part of Privacy Browser.
1135 genericIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1137 // Start the app or display a snackbar if no app is available to handle the URL.
1139 startActivity(genericIntent);
1140 } catch (ActivityNotFoundException exception) {
1141 Snackbar.make(mainWebView, getString(R.string.unrecognized_url) + " " + url, Snackbar.LENGTH_SHORT).show();
1144 // Returning true indicates Privacy Browser is handling the URL by creating an intent.
1149 // Check requests against the block lists. The deprecated `shouldInterceptRequest` must be used until minimum API >= 21.
1150 @SuppressWarnings("deprecation")
1152 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1153 // Create an empty web resource response to be used if the resource request is blocked.
1154 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1156 // Check EasyList if it is enabled.
1157 if (easyListEnabled) {
1158 if (blockListHelper.isBlocked(formattedUrlString, url, easyList)) {
1159 // The resource request was blocked. Return an empty web resource response.
1160 return emptyWebResourceResponse;
1164 // Check EasyPrivacy if it is enabled.
1165 if (easyPrivacyEnabled) {
1166 if (blockListHelper.isBlocked(formattedUrlString, url, easyPrivacy)) {
1167 // The resource request was blocked. Return an empty web resource response.
1168 return emptyWebResourceResponse;
1172 // Check Fanboy’s Annoyance List if it is enabled.
1173 if (fanboysAnnoyanceListEnabled) {
1174 if (blockListHelper.isBlocked(formattedUrlString, url, fanboyAnnoyance)) {
1175 // The resource request was blocked. Return an empty web resource response.
1176 return emptyWebResourceResponse;
1178 } else if (fanboysSocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
1179 if (blockListHelper.isBlocked(formattedUrlString, url, fanboySocial)) {
1180 // The resource request was blocked. Return an empty web resource response.
1181 return emptyWebResourceResponse;
1185 // The resource request has not been blocked. `return null` loads the requested resource.
1189 // Handle HTTP authentication requests.
1191 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1192 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1193 httpAuthHandler = handler;
1195 // Display the HTTP authentication dialog.
1196 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1197 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1200 // Update the URL in urlTextBox when the page starts to load.
1202 public void onPageStarted(WebView view, String url, Bitmap favicon) {// If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1204 mainWebView.setVisibility(View.INVISIBLE);
1207 // Hide the keyboard. `0` indicates no additional flags.
1208 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1210 // Check to see if we are waiting on Orbot.
1211 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1212 // 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.
1213 formattedUrlString = url;
1215 // Display the formatted URL text.
1216 urlTextBox.setText(formattedUrlString);
1218 // Apply text highlighting to `urlTextBox`.
1221 // Apply any custom domain settings if the URL was loaded by navigating history.
1222 if (navigatingHistory) {
1223 applyDomainSettings(url, true);
1226 // 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.
1227 urlIsLoading = true;
1231 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1233 public void onPageFinished(WebView view, String url) {
1234 // Flush any cookies to persistent storage. `CookieManager` has become very lazy about flushing cookies in recent versions.
1235 if (firstPartyCookiesEnabled && Build.VERSION.SDK_INT >= 21) {
1236 cookieManager.flush();
1239 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1240 urlIsLoading = false;
1242 // Clear the cache and history if Incognito Mode is enabled.
1243 if (incognitoModeEnabled) {
1244 // Clear the cache. `true` includes disk files.
1245 mainWebView.clearCache(true);
1247 // Clear the back/forward history.
1248 mainWebView.clearHistory();
1250 // Manually delete cache folders.
1252 // Delete the main cache directory.
1253 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1255 // Delete the secondary `Service Worker` cache directory.
1256 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1257 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1258 } catch (IOException e) {
1259 // Do nothing if an error is thrown.
1263 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1264 if (!waitingForOrbot) {
1265 // Check to see if `WebView` has set `url` to be `about:blank`.
1266 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1267 // Set `formattedUrlString` to `""`.
1268 formattedUrlString = "";
1270 urlTextBox.setText(formattedUrlString);
1272 // Request focus for `urlTextBox`.
1273 urlTextBox.requestFocus();
1275 // Display the keyboard.
1276 inputMethodManager.showSoftInput(urlTextBox, 0);
1278 // Apply the domain settings. This clears any settings from the previous domain.
1279 applyDomainSettings(formattedUrlString, true);
1280 } else { // `WebView` has loaded a webpage.
1281 // Set `formattedUrlString`.
1282 formattedUrlString = url;
1284 // Only update `urlTextBox` if the user is not typing in it.
1285 if (!urlTextBox.hasFocus()) {
1286 // Display the formatted URL text.
1287 urlTextBox.setText(formattedUrlString);
1289 // Apply text highlighting to `urlTextBox`.
1294 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1295 sslCertificate = mainWebView.getCertificate();
1297 // Check the current website SSL certificate against the pinned SSL certificate if there is a pinned SSL certificate the user has not chosen to ignore it for this session.
1298 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1299 // Initialize the current SSL certificate variables.
1300 String currentWebsiteIssuedToCName = "";
1301 String currentWebsiteIssuedToOName = "";
1302 String currentWebsiteIssuedToUName = "";
1303 String currentWebsiteIssuedByCName = "";
1304 String currentWebsiteIssuedByOName = "";
1305 String currentWebsiteIssuedByUName = "";
1306 Date currentWebsiteSslStartDate = null;
1307 Date currentWebsiteSslEndDate = null;
1310 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1311 if (sslCertificate != null) {
1312 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1313 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1314 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1315 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1316 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1317 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1318 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1319 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1322 // Initialize `String` variables to store the SSL certificate dates. `Strings` are needed to compare the values below, which doesn't work with `Dates` if they are `null`.
1323 String currentWebsiteSslStartDateString = "";
1324 String currentWebsiteSslEndDateString = "";
1325 String pinnedDomainSslStartDateString = "";
1326 String pinnedDomainSslEndDateString = "";
1328 // Convert the `Dates` to `Strings` if they are not `null`.
1329 if (currentWebsiteSslStartDate != null) {
1330 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1333 if (currentWebsiteSslEndDate != null) {
1334 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1337 if (pinnedDomainSslStartDate != null) {
1338 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1341 if (pinnedDomainSslEndDate != null) {
1342 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1345 // Check to see if the pinned SSL certificate matches the current website certificate.
1346 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1347 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1348 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1349 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1350 // The pinned SSL certificate doesn't match the current domain certificate.
1351 //Display the pinned SSL certificate mismatch `AlertDialog`.
1352 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1353 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1359 // Handle SSL Certificate errors.
1361 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1362 // Get the current website SSL certificate.
1363 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1365 // Extract the individual pieces of information from the current website SSL certificate.
1366 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1367 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1368 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1369 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1370 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1371 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1372 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1373 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1375 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1376 if (pinnedDomainSslCertificate &&
1377 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1378 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1379 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1380 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1381 // An SSL certificate is pinned and matches the current domain certificate.
1382 // Proceed to the website without displaying an error.
1384 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1385 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1386 sslErrorHandler = handler;
1388 // Display the SSL error `AlertDialog`.
1389 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1390 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1395 // Load the website if not waiting for Orbot to connect.
1396 if (!waitingForOrbot) {
1397 loadUrl(formattedUrlString);
1402 protected void onNewIntent(Intent intent) {
1403 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1406 // Check to see if the intent contains a new URL.
1407 if (intent.getData() != null) {
1408 // Get the intent data and convert it to a string.
1409 final Uri intentUriData = intent.getData();
1410 formattedUrlString = intentUriData.toString();
1412 // Load the website.
1413 loadUrl(formattedUrlString);
1415 // Close the navigation drawer if it is open.
1416 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1417 drawerLayout.closeDrawer(GravityCompat.START);
1420 // Close the bookmarks drawer if it is open.
1421 if (drawerLayout.isDrawerVisible(GravityCompat.END)) {
1422 drawerLayout.closeDrawer(GravityCompat.END);
1425 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1426 mainWebView.requestFocus();
1431 public void onRestart() {
1432 // Run the default commands.
1435 // Make sure Orbot is running if Privacy Browser is proxying through Orbot.
1436 if (proxyThroughOrbot) {
1437 // Request Orbot to start. If Orbot is already running no hard will be caused by this request.
1438 Intent orbotIntent = new Intent("org.torproject.android.intent.action.START");
1440 // Send the intent to the Orbot package.
1441 orbotIntent.setPackage("org.torproject.android");
1444 sendBroadcast(orbotIntent);
1447 // Apply the app settings if returning from the Settings activity..
1448 if (reapplyAppSettingsOnRestart) {
1449 // Apply the app settings.
1452 // Reload the webpage if displaying of images has been disabled in the Settings activity.
1453 if (reloadOnRestart) {
1454 // Reload `mainWebView`.
1455 mainWebView.reload();
1457 // Reset `reloadOnRestartBoolean`.
1458 reloadOnRestart = false;
1461 // Reset the return from settings flag.
1462 reapplyAppSettingsOnRestart = false;
1465 // Apply the domain settings if returning from the Domains activity.
1466 if (reapplyDomainSettingsOnRestart) {
1467 // Reapply the domain settings.
1468 applyDomainSettings(formattedUrlString, false);
1470 // Reset `reapplyDomainSettingsOnRestart`.
1471 reapplyDomainSettingsOnRestart = false;
1474 // Load the URL on restart to apply changes to night mode.
1475 if (loadUrlOnRestart) {
1476 // Load the current `formattedUrlString`.
1477 loadUrl(formattedUrlString);
1479 // Reset `loadUrlOnRestart.
1480 loadUrlOnRestart = false;
1483 // Update the bookmarks drawer if returning from the Bookmarks activity.
1484 if (restartFromBookmarksActivity) {
1485 // Close the bookmarks drawer.
1486 drawerLayout.closeDrawer(GravityCompat.END);
1488 // Reload the bookmarks drawer.
1489 loadBookmarksFolder();
1491 // Reset `restartFromBookmarksActivity`.
1492 restartFromBookmarksActivity = false;
1495 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step. This can be important if the screen was rotated.
1496 updatePrivacyIcons(true);
1499 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1501 public void onResume() {
1502 // Run the default commands.
1505 // Resume JavaScript (if enabled).
1506 mainWebView.resumeTimers();
1508 // Resume `mainWebView`.
1509 mainWebView.onResume();
1511 // Resume the adView for the free flavor.
1512 if (BuildConfig.FLAVOR.contentEquals("free")) {
1513 BannerAd.resumeAd(adView);
1518 public void onPause() {
1519 // Pause `mainWebView`.
1520 mainWebView.onPause();
1522 // Stop all JavaScript.
1523 mainWebView.pauseTimers();
1525 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1526 if (BuildConfig.FLAVOR.contentEquals("free")) {
1527 BannerAd.pauseAd(adView);
1534 public boolean onCreateOptionsMenu(Menu menu) {
1535 // Inflate the menu; this adds items to the action bar if it is present.
1536 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1538 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1541 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1542 updatePrivacyIcons(false);
1544 // Get handles for the menu items.
1545 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1546 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1547 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1548 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1550 // Only display third-party cookies if SDK >= 21
1551 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1553 // Get the shared preference values. `this` references the current context.
1554 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1556 // Set the status of the additional app bar icons. The default is `false`.
1557 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1558 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1559 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1560 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1561 } else { //Do not display the additional icons.
1562 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1563 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1564 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1571 public boolean onPrepareOptionsMenu(Menu menu) {
1572 // Get handles for the menu items.
1573 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1574 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1575 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1576 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1577 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1578 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1579 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1580 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1581 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1582 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1583 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1584 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1586 // Set the text for the domain menu item.
1587 if (domainSettingsApplied) {
1588 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1590 addOrEditDomain.setTitle(R.string.add_domain_settings);
1593 // Set the status of the menu item checkboxes.
1594 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1595 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1596 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1597 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1598 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1600 // Enable third-party cookies if first-party cookies are enabled.
1601 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1603 // Enable `DOM Storage` if JavaScript is enabled.
1604 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1606 // Enable `Clear Cookies` if there are any.
1607 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1609 // Get a count of the number of files in the `Local Storage` directory.
1610 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1611 int localStorageDirectoryNumberOfFiles = 0;
1612 if (localStorageDirectory.exists()) {
1613 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1616 // Get a count of the number of files in the `IndexedDB` directory.
1617 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1618 int indexedDBDirectoryNumberOfFiles = 0;
1619 if (indexedDBDirectory.exists()) {
1620 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1623 // Enable `Clear DOM Storage` if there is any.
1624 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1626 // Enable `Clear Form Data` is there is any.
1627 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1628 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1630 // Enable `Clear Data` if any of the submenu items are enabled.
1631 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1633 // Initialize font size variables.
1634 int fontSize = mainWebView.getSettings().getTextZoom();
1635 String fontSizeTitle;
1636 MenuItem selectedFontSizeMenuItem;
1638 // Prepare the font size title and current size menu item.
1641 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1642 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1646 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1647 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1651 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1652 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1656 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1657 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1661 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1662 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1666 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1667 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1671 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1672 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1676 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1677 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1681 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1682 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1686 // Set the font size title and select the current size menu item.
1687 fontSizeMenuItem.setTitle(fontSizeTitle);
1688 selectedFontSizeMenuItem.setChecked(true);
1690 // Only show `Refresh` if `swipeToRefresh` is disabled.
1691 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1693 // Run all the other default commands.
1694 super.onPrepareOptionsMenu(menu);
1696 // Display the menu.
1701 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1702 @SuppressLint("SetJavaScriptEnabled")
1703 // removeAllCookies is deprecated, but it is required for API < 21.
1704 @SuppressWarnings("deprecation")
1705 public boolean onOptionsItemSelected(MenuItem menuItem) {
1706 // Get the selected menu item ID.
1707 int menuItemId = menuItem.getItemId();
1709 // Set the commands that relate to the menu entries.
1710 switch (menuItemId) {
1711 case R.id.add_or_edit_domain:
1712 if (domainSettingsApplied) { // Edit the current domain settings.
1713 // Reapply the domain settings on returning to `MainWebViewActivity`.
1714 reapplyDomainSettingsOnRestart = true;
1715 currentDomainName = "";
1717 // Create an intent to launch the domains activity.
1718 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1720 // Put extra information instructing the domains activity to directly load the current domain.
1721 domainsIntent.putExtra("LoadDomain", domainSettingsDatabaseId);
1724 startActivity(domainsIntent);
1725 } else { // Add a new domain.
1726 // Apply the new domain settings on returning to `MainWebViewActivity`.
1727 reapplyDomainSettingsOnRestart = true;
1728 currentDomainName = "";
1730 // Get the current domain
1731 Uri currentUri = Uri.parse(formattedUrlString);
1732 String currentDomain = currentUri.getHost();
1734 // Initialize the database handler. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
1735 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
1737 // Create the domain and store the database ID.
1738 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(currentDomain);
1740 // Create an intent to launch the domains activity.
1741 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1743 // Put extra information instructing the domains activity to directly load the new domain.
1744 domainsIntent.putExtra("LoadDomain", newDomainDatabaseId);
1747 startActivity(domainsIntent);
1751 case R.id.toggle_javascript:
1752 // Switch the status of javaScriptEnabled.
1753 javaScriptEnabled = !javaScriptEnabled;
1755 // Apply the new JavaScript status.
1756 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1758 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1759 updatePrivacyIcons(true);
1761 // Display a `Snackbar`.
1762 if (javaScriptEnabled) { // JavaScrip is enabled.
1763 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1764 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1765 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1766 } else { // Privacy mode.
1767 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1770 // Reload the WebView.
1771 mainWebView.reload();
1774 case R.id.toggle_first_party_cookies:
1775 // Switch the status of firstPartyCookiesEnabled.
1776 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1778 // Update the menu checkbox.
1779 menuItem.setChecked(firstPartyCookiesEnabled);
1781 // Apply the new cookie status.
1782 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1784 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1785 updatePrivacyIcons(true);
1787 // Display a `Snackbar`.
1788 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1789 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1790 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1791 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1792 } else { // Privacy mode.
1793 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1796 // Reload the WebView.
1797 mainWebView.reload();
1800 case R.id.toggle_third_party_cookies:
1801 if (Build.VERSION.SDK_INT >= 21) {
1802 // Switch the status of thirdPartyCookiesEnabled.
1803 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1805 // Update the menu checkbox.
1806 menuItem.setChecked(thirdPartyCookiesEnabled);
1808 // Apply the new cookie status.
1809 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1811 // Display a `Snackbar`.
1812 if (thirdPartyCookiesEnabled) {
1813 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1815 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1818 // Reload the WebView.
1819 mainWebView.reload();
1820 } // Else do nothing because SDK < 21.
1823 case R.id.toggle_dom_storage:
1824 // Switch the status of domStorageEnabled.
1825 domStorageEnabled = !domStorageEnabled;
1827 // Update the menu checkbox.
1828 menuItem.setChecked(domStorageEnabled);
1830 // Apply the new DOM Storage status.
1831 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1833 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1834 updatePrivacyIcons(true);
1836 // Display a `Snackbar`.
1837 if (domStorageEnabled) {
1838 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1840 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1843 // Reload the WebView.
1844 mainWebView.reload();
1847 case R.id.toggle_save_form_data:
1848 // Switch the status of saveFormDataEnabled.
1849 saveFormDataEnabled = !saveFormDataEnabled;
1851 // Update the menu checkbox.
1852 menuItem.setChecked(saveFormDataEnabled);
1854 // Apply the new form data status.
1855 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1857 // Display a `Snackbar`.
1858 if (saveFormDataEnabled) {
1859 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1861 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1864 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1865 updatePrivacyIcons(true);
1867 // Reload the WebView.
1868 mainWebView.reload();
1871 case R.id.clear_cookies:
1872 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1873 .setAction(R.string.undo, v -> {
1874 // Do nothing because everything will be handled by `onDismissed()` below.
1876 .addCallback(new Snackbar.Callback() {
1878 public void onDismissed(Snackbar snackbar, int event) {
1880 // The user pushed the `Undo` button.
1881 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1885 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1887 // `cookieManager.removeAllCookie()` varies by SDK.
1888 if (Build.VERSION.SDK_INT < 21) {
1889 cookieManager.removeAllCookie();
1891 // `null` indicates no callback.
1892 cookieManager.removeAllCookies(null);
1900 case R.id.clear_dom_storage:
1901 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1902 .setAction(R.string.undo, v -> {
1903 // Do nothing because everything will be handled by `onDismissed()` below.
1905 .addCallback(new Snackbar.Callback() {
1907 public void onDismissed(Snackbar snackbar, int event) {
1909 // The user pushed the `Undo` button.
1910 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1914 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1916 // Delete the DOM Storage.
1917 WebStorage webStorage = WebStorage.getInstance();
1918 webStorage.deleteAllData();
1920 // Manually delete the DOM storage files and directories.
1922 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1923 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1925 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1926 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1927 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1928 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1929 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1930 } catch (IOException e) {
1931 // Do nothing if an error is thrown.
1939 case R.id.clear_form_data:
1940 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1941 .setAction(R.string.undo, v -> {
1942 // Do nothing because everything will be handled by `onDismissed()` below.
1944 .addCallback(new Snackbar.Callback() {
1946 public void onDismissed(Snackbar snackbar, int event) {
1948 // The user pushed the `Undo` button.
1949 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1953 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1955 // Delete the form data.
1956 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1957 mainWebViewDatabase.clearFormData();
1964 case R.id.font_size_twenty_five_percent:
1965 mainWebView.getSettings().setTextZoom(25);
1968 case R.id.font_size_fifty_percent:
1969 mainWebView.getSettings().setTextZoom(50);
1972 case R.id.font_size_seventy_five_percent:
1973 mainWebView.getSettings().setTextZoom(75);
1976 case R.id.font_size_one_hundred_percent:
1977 mainWebView.getSettings().setTextZoom(100);
1980 case R.id.font_size_one_hundred_twenty_five_percent:
1981 mainWebView.getSettings().setTextZoom(125);
1984 case R.id.font_size_one_hundred_fifty_percent:
1985 mainWebView.getSettings().setTextZoom(150);
1988 case R.id.font_size_one_hundred_seventy_five_percent:
1989 mainWebView.getSettings().setTextZoom(175);
1992 case R.id.font_size_two_hundred_percent:
1993 mainWebView.getSettings().setTextZoom(200);
1996 case R.id.display_images:
1997 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1998 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1999 mainWebView.reload();
2000 } else { // Images are not currently loaded automatically.
2001 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2004 // Set `onTheFlyDisplayImagesSet`.
2005 onTheFlyDisplayImagesSet = true;
2009 // Setup the share string.
2010 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2012 // Create the share intent.
2013 Intent shareIntent = new Intent();
2014 shareIntent.setAction(Intent.ACTION_SEND);
2015 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2016 shareIntent.setType("text/plain");
2019 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2022 case R.id.find_on_page:
2023 // Hide the URL app bar.
2024 supportAppBar.setVisibility(View.GONE);
2026 // Show the Find on Page `RelativeLayout`.
2027 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2029 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2030 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2031 findOnPageEditText.postDelayed(() -> {
2032 // Set the focus on `findOnPageEditText`.
2033 findOnPageEditText.requestFocus();
2035 // Display the keyboard. `0` sets no input flags.
2036 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2041 // Get a `PrintManager` instance.
2042 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2044 // Convert `mainWebView` to `printDocumentAdapter`.
2045 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2047 // Remove the lint error below that `printManager` might be `null`.
2048 assert printManager != null;
2050 // Print the document. The print attributes are `null`.
2051 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2054 case R.id.view_source:
2055 // Launch the Vew Source activity.
2056 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2057 startActivity(viewSourceIntent);
2060 case R.id.add_to_homescreen:
2061 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2062 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2063 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2065 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2069 mainWebView.reload();
2073 // Don't consume the event.
2074 return super.onOptionsItemSelected(menuItem);
2078 // removeAllCookies is deprecated, but it is required for API < 21.
2079 @SuppressWarnings("deprecation")
2081 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2082 int menuItemId = menuItem.getItemId();
2084 switch (menuItemId) {
2090 if (mainWebView.canGoBack()) {
2091 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2092 navigatingHistory = true;
2094 // Load the previous website in the history.
2095 mainWebView.goBack();
2100 if (mainWebView.canGoForward()) {
2101 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2102 navigatingHistory = true;
2104 // Load the next website in the history.
2105 mainWebView.goForward();
2110 // Get the `WebBackForwardList`.
2111 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2113 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2114 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2115 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2118 case R.id.downloads:
2119 // Launch the system Download Manager.
2120 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2122 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2123 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2125 startActivity(downloadManagerIntent);
2129 // Set the flag to reapply the domain settings on restart when returning from Domain Settings.
2130 reapplyDomainSettingsOnRestart = true;
2131 currentDomainName = "";
2133 // Launch `DomainsActivity`.
2134 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2135 startActivity(domainsIntent);
2139 // Set the flag to reapply app settings on restart when returning from Settings.
2140 reapplyAppSettingsOnRestart = true;
2142 // Set the flag to reapply the domain settings on restart when returning from Settings.
2143 reapplyDomainSettingsOnRestart = true;
2144 currentDomainName = "";
2146 // Launch `SettingsActivity`.
2147 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2148 startActivity(settingsIntent);
2152 // Launch `GuideActivity`.
2153 Intent guideIntent = new Intent(this, GuideActivity.class);
2154 startActivity(guideIntent);
2158 // Launch `AboutActivity`.
2159 Intent aboutIntent = new Intent(this, AboutActivity.class);
2160 startActivity(aboutIntent);
2163 case R.id.clearAndExit:
2164 // Get a handle for `sharedPreferences`. `this` references the current context.
2165 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2167 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2170 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2171 // The command to remove cookies changed slightly in API 21.
2172 if (Build.VERSION.SDK_INT >= 21) {
2173 cookieManager.removeAllCookies(null);
2175 cookieManager.removeAllCookie();
2178 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2180 // We have to use two commands because `Runtime.exec()` does not like `*`.
2181 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2182 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2183 } catch (IOException e) {
2184 // Do nothing if an error is thrown.
2188 // Clear DOM storage.
2189 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2190 // Ask `WebStorage` to clear the DOM storage.
2191 WebStorage webStorage = WebStorage.getInstance();
2192 webStorage.deleteAllData();
2194 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2196 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2197 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2199 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2200 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2201 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2202 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2203 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2204 } catch (IOException e) {
2205 // Do nothing if an error is thrown.
2210 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2211 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2212 webViewDatabase.clearFormData();
2214 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2216 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2217 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2218 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2219 } catch (IOException e) {
2220 // Do nothing if an error is thrown.
2225 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2226 // `true` includes disk files.
2227 mainWebView.clearCache(true);
2229 // Manually delete the cache directories.
2231 // Delete the main cache directory.
2232 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2234 // Delete the secondary `Service Worker` cache directory.
2235 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2236 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2237 } catch (IOException e) {
2238 // Do nothing if an error is thrown.
2242 // Clear SSL certificate preferences.
2243 mainWebView.clearSslPreferences();
2245 // Clear the back/forward history.
2246 mainWebView.clearHistory();
2248 // Clear `formattedUrlString`.
2249 formattedUrlString = null;
2251 // Clear `customHeaders`.
2252 customHeaders.clear();
2254 // Detach all views from `mainWebViewRelativeLayout`.
2255 mainWebViewRelativeLayout.removeAllViews();
2257 // Destroy the internal state of `mainWebView`.
2258 mainWebView.destroy();
2260 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2261 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2262 if (clearEverything) {
2264 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2265 } catch (IOException e) {
2266 // Do nothing if an error is thrown.
2270 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2271 if (Build.VERSION.SDK_INT >= 21) {
2272 finishAndRemoveTask();
2277 // Remove the terminated program from RAM. The status code is `0`.
2282 // Close the navigation drawer.
2283 drawerLayout.closeDrawer(GravityCompat.START);
2288 public void onPostCreate(Bundle savedInstanceState) {
2289 super.onPostCreate(savedInstanceState);
2291 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2292 drawerToggle.syncState();
2296 public void onConfigurationChanged(Configuration newConfig) {
2297 super.onConfigurationChanged(newConfig);
2299 // Reload the ad for the free flavor if we are not in full screen mode.
2300 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2302 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2304 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2305 adView = findViewById(R.id.adview);
2308 // `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:
2309 // https://code.google.com/p/android/issues/detail?id=20493#c8
2310 // ActivityCompat.invalidateOptionsMenu(this);
2314 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2315 // Store the `HitTestResult`.
2316 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2319 final String imageUrl;
2320 final String linkUrl;
2322 // Get a handle for the `ClipboardManager`.
2323 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2325 // Remove the lint errors below that `clipboardManager` might be `null`.
2326 assert clipboardManager != null;
2328 switch (hitTestResult.getType()) {
2329 // `SRC_ANCHOR_TYPE` is a link.
2330 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2331 // Get the target URL.
2332 linkUrl = hitTestResult.getExtra();
2334 // Set the target URL as the title of the `ContextMenu`.
2335 menu.setHeaderTitle(linkUrl);
2337 // Add a `Load URL` entry.
2338 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
2343 // Add a `Copy URL` entry.
2344 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2345 // Save the link URL in a `ClipData`.
2346 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2348 // Set the `ClipData` as the clipboard's primary clip.
2349 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2353 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2354 menu.add(R.string.cancel);
2357 case WebView.HitTestResult.EMAIL_TYPE:
2358 // Get the target URL.
2359 linkUrl = hitTestResult.getExtra();
2361 // Set the target URL as the title of the `ContextMenu`.
2362 menu.setHeaderTitle(linkUrl);
2364 // Add a `Write Email` entry.
2365 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2366 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2367 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2369 // Parse the url and set it as the data for the `Intent`.
2370 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2372 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2373 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2376 startActivity(emailIntent);
2380 // Add a `Copy Email Address` entry.
2381 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2382 // Save the email address in a `ClipData`.
2383 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2385 // Set the `ClipData` as the clipboard's primary clip.
2386 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2390 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2391 menu.add(R.string.cancel);
2394 // `IMAGE_TYPE` is an image.
2395 case WebView.HitTestResult.IMAGE_TYPE:
2396 // Get the image URL.
2397 imageUrl = hitTestResult.getExtra();
2399 // Set the image URL as the title of the `ContextMenu`.
2400 menu.setHeaderTitle(imageUrl);
2402 // Add a `View Image` entry.
2403 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2408 // Add a `Download Image` entry.
2409 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2410 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2411 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2412 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2414 // Store the image URL for use by `onRequestPermissionResult()`.
2415 downloadImageUrl = imageUrl;
2417 // Show a dialog if the user has previously denied the permission.
2418 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2419 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2420 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2422 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2423 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2424 } else { // Show the permission request directly.
2425 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2426 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2428 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2429 // Get a handle for the download image alert dialog.
2430 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2432 // Show the download image alert dialog.
2433 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2438 // Add a `Copy URL` entry.
2439 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2440 // Save the image URL in a `ClipData`.
2441 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2443 // Set the `ClipData` as the clipboard's primary clip.
2444 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2448 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2449 menu.add(R.string.cancel);
2453 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2454 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2455 // Get the image URL.
2456 imageUrl = hitTestResult.getExtra();
2458 // Set the image URL as the title of the `ContextMenu`.
2459 menu.setHeaderTitle(imageUrl);
2461 // Add a `View Image` entry.
2462 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2467 // Add a `Download Image` entry.
2468 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2469 // Check to see if the WRITE_EXTERNAL_STORAGE permission has already been granted.
2470 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
2471 // The WRITE_EXTERNAL_STORAGE permission needs to be requested.
2473 // Store the image URL for use by `onRequestPermissionResult()`.
2474 downloadImageUrl = imageUrl;
2476 // Show a dialog if the user has previously denied the permission.
2477 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show a dialog explaining the request first.
2478 // Get a handle for the download location permission alert dialog and set the download type to DOWNLOAD_IMAGE.
2479 DialogFragment downloadLocationPermissionDialogFragment = DownloadLocationPermissionDialog.downloadType(DownloadLocationPermissionDialog.DOWNLOAD_IMAGE);
2481 // Show the download location permission alert dialog. The permission will be requested when the dialog is closed.
2482 downloadLocationPermissionDialogFragment.show(getFragmentManager(), getString(R.string.download_location));
2483 } else { // Show the permission request directly.
2484 // Request the permission. The download dialog will be launched by `onRequestPermissionResult().
2485 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2487 } else { // The WRITE_EXTERNAL_STORAGE permission has already been granted.
2488 // Get a handle for the download image alert dialog.
2489 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2491 // Show the download image alert dialog.
2492 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2497 // Add a `Copy URL` entry.
2498 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2499 // Save the image URL in a `ClipData`.
2500 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2502 // Set the `ClipData` as the clipboard's primary clip.
2503 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2507 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2508 menu.add(R.string.cancel);
2514 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2515 // Get the `EditTexts` from the `dialogFragment`.
2516 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2517 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2519 // Extract the strings from the `EditTexts`.
2520 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2521 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2523 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2524 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2525 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2526 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2528 // Display the new bookmark below the current items in the (0 indexed) list.
2529 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2531 // Create the bookmark.
2532 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2534 // Update `bookmarksCursor` with the current contents of this folder.
2535 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2537 // Update the `ListView`.
2538 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2540 // Scroll to the new bookmark.
2541 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2545 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2546 // Get handles for the views in `dialogFragment`.
2547 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2548 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2549 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2551 // Get new folder name string.
2552 String folderNameString = createFolderNameEditText.getText().toString();
2554 // Get the new folder icon `Bitmap`.
2555 Bitmap folderIconBitmap;
2556 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2557 // Get the default folder icon and convert it to a `Bitmap`.
2558 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2559 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2560 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2561 } else { // Use the `WebView` favorite icon.
2562 folderIconBitmap = favoriteIconBitmap;
2565 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2566 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2567 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2568 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2570 // Move all the bookmarks down one in the display order.
2571 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2572 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2573 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2576 // Create the folder, which will be placed at the top of the `ListView`.
2577 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2579 // Update `bookmarksCursor` with the current contents of this folder.
2580 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2582 // Update the `ListView`.
2583 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2585 // Scroll to the new folder.
2586 bookmarksListView.setSelection(0);
2590 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2591 // Get the shortcut name.
2592 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2593 String shortcutNameString = shortcutNameEditText.getText().toString();
2595 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2596 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2598 // Setup the shortcut intent.
2599 Intent shortcutIntent = new Intent();
2600 shortcutIntent.setAction(Intent.ACTION_VIEW);
2601 shortcutIntent.setData(Uri.parse(formattedUrlString));
2603 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2604 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2606 // Add the required fields to the shortcut info builder.
2607 shortcutInfoBuilder.setIcon(favoriteIcon);
2608 shortcutInfoBuilder.setIntent(shortcutIntent);
2609 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2611 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2612 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2616 public void onCloseDownloadLocationPermissionDialog(int downloadType) {
2617 switch (downloadType) {
2618 case DownloadLocationPermissionDialog.DOWNLOAD_FILE:
2619 // Request the WRITE_EXTERNAL_STORAGE permission with a file request code.
2620 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_FILE_REQUEST_CODE);
2623 case DownloadLocationPermissionDialog.DOWNLOAD_IMAGE:
2624 // Request the WRITE_EXTERNAL_STORAGE permission with an image request code.
2625 ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, DOWNLOAD_IMAGE_REQUEST_CODE);
2631 public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
2632 switch (requestCode) {
2633 case DOWNLOAD_FILE_REQUEST_CODE:
2634 // Show the download file alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2635 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(downloadUrl, downloadContentDisposition, downloadContentLength);
2637 // On API 23, displaying the fragment must be delayed or the app will crash.
2638 if (Build.VERSION.SDK_INT == 23) {
2639 new Handler().postDelayed(() -> downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2641 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2644 // Reset the download variables.
2646 downloadContentDisposition = "";
2647 downloadContentLength = 0;
2650 case DOWNLOAD_IMAGE_REQUEST_CODE:
2651 // Show the download image alert dialog. When the dialog closes, the correct command will be used based on the permission status.
2652 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(downloadImageUrl);
2654 // On API 23, displaying the fragment must be delayed or the app will crash.
2655 if (Build.VERSION.SDK_INT == 23) {
2656 new Handler().postDelayed(() -> downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download)), 500);
2658 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2661 // Reset the image URL variable.
2662 downloadImageUrl = "";
2668 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2669 // Download the image if it has an HTTP or HTTPS URI.
2670 if (imageUrl.startsWith("http")) {
2671 // Get a handle for the system `DOWNLOAD_SERVICE`.
2672 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2674 // Parse `imageUrl`.
2675 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2677 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2678 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2679 if (firstPartyCookiesEnabled) {
2680 // Get the cookies for `imageUrl`.
2681 String cookies = cookieManager.getCookie(imageUrl);
2683 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2684 downloadRequest.addRequestHeader("Cookie", cookies);
2687 // Get the file name from the dialog fragment.
2688 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2689 String imageName = downloadImageNameEditText.getText().toString();
2691 // Specify the download location.
2692 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2693 // Download to the public download directory.
2694 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, imageName);
2695 } else { // External write permission denied.
2696 // Download to the app's external download directory.
2697 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, imageName);
2700 // Allow `MediaScanner` to index the download if it is a media file.
2701 downloadRequest.allowScanningByMediaScanner();
2703 // Add the URL as the description for the download.
2704 downloadRequest.setDescription(imageUrl);
2706 // Show the download notification after the download is completed.
2707 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2709 // Remove the lint warning below that `downloadManager` might be `null`.
2710 assert downloadManager != null;
2712 // Initiate the download.
2713 downloadManager.enqueue(downloadRequest);
2714 } else { // The image is not an HTTP or HTTPS URI.
2715 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2720 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2721 // Download the file if it has an HTTP or HTTPS URI.
2722 if (downloadUrl.startsWith("http")) {
2723 // Get a handle for the system `DOWNLOAD_SERVICE`.
2724 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2726 // Parse `downloadUrl`.
2727 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2729 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2730 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2731 if (firstPartyCookiesEnabled) {
2732 // Get the cookies for `downloadUrl`.
2733 String cookies = cookieManager.getCookie(downloadUrl);
2735 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2736 downloadRequest.addRequestHeader("Cookie", cookies);
2739 // Get the file name from the dialog fragment.
2740 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2741 String fileName = downloadFileNameEditText.getText().toString();
2743 // Specify the download location.
2744 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // External write permission granted.
2745 // Download to the public download directory.
2746 downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
2747 } else { // External write permission denied.
2748 // Download to the app's external download directory.
2749 downloadRequest.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, fileName);
2752 // Allow `MediaScanner` to index the download if it is a media file.
2753 downloadRequest.allowScanningByMediaScanner();
2755 // Add the URL as the description for the download.
2756 downloadRequest.setDescription(downloadUrl);
2758 // Show the download notification after the download is completed.
2759 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2761 // Remove the lint warning below that `downloadManager` might be `null`.
2762 assert downloadManager != null;
2764 // Initiate the download.
2765 downloadManager.enqueue(downloadRequest);
2766 } else { // The download is not an HTTP or HTTPS URI.
2767 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2772 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2773 // Get handles for the views from `dialogFragment`.
2774 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2775 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2776 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2778 // Store the bookmark strings.
2779 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2780 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2782 // Update the bookmark.
2783 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2784 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2785 } else { // Update the bookmark using the `WebView` favorite icon.
2786 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2787 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2788 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2789 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2791 // Update the bookmark and the favorite icon.
2792 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2795 // Update `bookmarksCursor` with the current contents of this folder.
2796 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2798 // Update the `ListView`.
2799 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2803 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2804 // Get handles for the views from `dialogFragment`.
2805 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2806 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2807 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2808 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2810 // Get the new folder name.
2811 String newFolderNameString = editFolderNameEditText.getText().toString();
2813 // Check if the favorite icon has changed.
2814 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2815 // Update the name in the database.
2816 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2817 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2818 // Get the new folder icon `Bitmap`.
2819 Bitmap folderIconBitmap;
2820 if (defaultFolderIconRadioButton.isChecked()) {
2821 // Get the default folder icon and convert it to a `Bitmap`.
2822 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2823 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2824 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2825 } else { // Use the `WebView` favorite icon.
2826 folderIconBitmap = favoriteIconBitmap;
2829 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2830 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2831 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2832 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2834 // Update the folder icon in the database.
2835 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2836 } else { // The folder icon and the name have changed.
2837 // Get the new folder icon `Bitmap`.
2838 Bitmap folderIconBitmap;
2839 if (defaultFolderIconRadioButton.isChecked()) {
2840 // Get the default folder icon and convert it to a `Bitmap`.
2841 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2842 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2843 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2844 } else { // Use the `WebView` favorite icon.
2845 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2848 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2849 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2850 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2851 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2853 // Update the folder name and icon in the database.
2854 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2857 // Update `bookmarksCursor` with the current contents of this folder.
2858 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2860 // Update the `ListView`.
2861 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2865 public void onHttpAuthenticationCancel() {
2866 // Cancel the `HttpAuthHandler`.
2867 httpAuthHandler.cancel();
2871 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2872 // Get handles for the `EditTexts`.
2873 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2874 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2876 // Proceed with the HTTP authentication.
2877 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2880 public void viewSslCertificate(View view) {
2881 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2882 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2883 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2887 public void onSslErrorCancel() {
2888 sslErrorHandler.cancel();
2892 public void onSslErrorProceed() {
2893 sslErrorHandler.proceed();
2897 public void onSslMismatchBack() {
2898 if (mainWebView.canGoBack()) { // There is a back page in the history.
2899 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2900 navigatingHistory = true;
2903 mainWebView.goBack();
2904 } else { // There are no pages to go back to.
2905 // Load a blank page
2911 public void onSslMismatchProceed() {
2912 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2913 ignorePinnedSslCertificate = true;
2917 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2918 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2919 navigatingHistory = true;
2921 // Load the history entry.
2922 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2926 public void onClearHistory() {
2927 // Clear the history.
2928 mainWebView.clearHistory();
2931 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2933 public void onBackPressed() {
2934 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2935 // Close the navigation drawer.
2936 drawerLayout.closeDrawer(GravityCompat.START);
2937 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2938 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2939 // close the bookmarks drawer.
2940 drawerLayout.closeDrawer(GravityCompat.END);
2941 } else { // A subfolder is displayed.
2942 // Place the former parent folder in `currentFolder`.
2943 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2945 // Load the new folder.
2946 loadBookmarksFolder();
2949 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2950 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2951 navigatingHistory = true;
2954 mainWebView.goBack();
2955 } else { // There isn't anything to do in Privacy Browser.
2956 // Pass `onBackPressed()` to the system.
2957 super.onBackPressed();
2961 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2962 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2963 String unformattedUrlString = urlTextBox.getText().toString().trim();
2965 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2966 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2967 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2968 if (!unformattedUrlString.startsWith("http")) {
2969 unformattedUrlString = "http://" + unformattedUrlString;
2972 // Initialize `unformattedUrl`.
2973 URL unformattedUrl = null;
2975 // 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.
2977 unformattedUrl = new URL(unformattedUrlString);
2978 } catch (MalformedURLException e) {
2979 e.printStackTrace();
2982 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2983 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2984 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2985 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2986 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2987 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2990 Uri.Builder formattedUri = new Uri.Builder();
2991 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2993 // Decode `formattedUri` as a `String` in `UTF-8`.
2994 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2996 // Sanitize the search input and convert it to a search.
2997 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2999 // Add the base search URL.
3000 formattedUrlString = searchURL + encodedUrlString;
3003 // 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.
3004 urlTextBox.clearFocus();
3006 loadUrl(formattedUrlString);
3010 private void loadUrl(String url) {
3011 // Apply any custom domain settings.
3012 applyDomainSettings(url, true);
3015 mainWebView.loadUrl(url, customHeaders);
3017 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3018 urlIsLoading = true;
3021 public void findPreviousOnPage(View view) {
3022 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3023 mainWebView.findNext(false);
3026 public void findNextOnPage(View view) {
3027 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3028 mainWebView.findNext(true);
3031 public void closeFindOnPage(View view) {
3032 // Delete the contents of `find_on_page_edittext`.
3033 findOnPageEditText.setText(null);
3035 // Clear the highlighted phrases.
3036 mainWebView.clearMatches();
3038 // Hide the Find on Page `RelativeLayout`.
3039 findOnPageLinearLayout.setVisibility(View.GONE);
3041 // Show the URL app bar.
3042 supportAppBar.setVisibility(View.VISIBLE);
3044 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3045 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3048 private void applyAppSettings() {
3049 // Get a handle for the shared preferences.
3050 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3052 // Store the values from the shared preferences in variables.
3053 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3054 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3055 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3056 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3057 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3058 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3059 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3060 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3061 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3062 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3063 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3064 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3065 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
3066 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3068 // Set the homepage, search, and proxy options.
3069 if (proxyThroughOrbot) { // Set the Tor options.
3070 // Set `torHomepageString` as `homepage`.
3071 homepage = torHomepageString;
3073 // If formattedUrlString is null assign the homepage to it.
3074 if (formattedUrlString == null) {
3075 formattedUrlString = homepage;
3078 // Set the search URL.
3079 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3080 searchURL = torSearchCustomURLString;
3081 } else { // Use the string from the pre-built list.
3082 searchURL = torSearchString;
3085 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3086 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3088 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3090 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3092 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3095 // Display a message to the user if we are waiting on Orbot.
3096 if (!orbotStatus.equals("ON")) {
3097 // Set `waitingForOrbot`.
3098 waitingForOrbot = true;
3100 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3101 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3103 } else { // Set the non-Tor options.
3104 // Set `homepageString` as `homepage`.
3105 homepage = homepageString;
3107 // If formattedUrlString is null assign the homepage to it.
3108 if (formattedUrlString == null) {
3109 formattedUrlString = homepage;
3112 // Set the search URL.
3113 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3114 searchURL = searchCustomURLString;
3115 } else { // Use the string from the pre-built list.
3116 searchURL = searchString;
3119 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3120 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3122 // Set the default `appBar` background. `this` refers to the context.
3124 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3126 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3129 // Reset `waitingForOrbot.
3130 waitingForOrbot = false;
3133 // Set swipe to refresh.
3134 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
3136 // Set Do Not Track status.
3137 if (doNotTrackEnabled) {
3138 customHeaders.put("DNT", "1");
3140 customHeaders.remove("DNT");
3143 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3144 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3145 if (hideSystemBarsOnFullscreen) { // Hide everything.
3146 // Remove the translucent navigation setting if it is currently flagged.
3147 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3149 // Remove the translucent status bar overlay.
3150 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3152 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3153 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3155 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3156 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3157 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
3159 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3160 } else { // Hide everything except the status and navigation bars.
3161 // Add the translucent status flag if it is unset.
3162 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3164 if (translucentNavigationBarOnFullscreen) {
3165 // Set the navigation bar to be translucent.
3166 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3168 // Set the navigation bar to be black.
3169 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3172 } else { // Switch to normal viewing mode.
3173 // Reset `inFullScreenBrowsingMode` to `false`.
3174 inFullScreenBrowsingMode = false;
3176 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3177 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3181 // Show the `BannerAd` in the free flavor.
3182 if (BuildConfig.FLAVOR.contentEquals("free")) {
3183 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
3184 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
3186 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3187 adView = findViewById(R.id.adview);
3190 // Remove the translucent navigation bar flag if it is set.
3191 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3193 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3194 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3196 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3197 rootCoordinatorLayout.setSystemUiVisibility(0);
3199 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3200 rootCoordinatorLayout.setFitsSystemWindows(true);
3205 // The deprecated `.getDrawable()` must be used until the minimum API >= 21.
3206 @SuppressWarnings("deprecation")
3207 private void applyDomainSettings(String url, boolean resetFavoriteIcon) {
3208 // Reset `navigatingHistory`.
3209 navigatingHistory = false;
3211 // Parse the URL into a URI.
3212 Uri uri = Uri.parse(url);
3214 // Extract the domain from `uri`.
3215 String hostName = uri.getHost();
3217 // Initialize `loadingNewDomainName`.
3218 boolean loadingNewDomainName;
3220 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3221 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3222 //noinspection SimplifiableIfStatement
3223 if ((hostName == null) || (currentDomainName == null)) {
3224 loadingNewDomainName = true;
3225 } else { // Determine if `hostName` equals `currentDomainName`.
3226 loadingNewDomainName = !hostName.equals(currentDomainName);
3229 // 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.
3230 if (loadingNewDomainName) {
3231 // Set the new `hostname` as the `currentDomainName`.
3232 currentDomainName = hostName;
3234 // Reset `ignorePinnedSslCertificate`.
3235 ignorePinnedSslCertificate = false;
3237 // Reset the favorite icon if specified.
3238 if (resetFavoriteIcon) {
3239 favoriteIconBitmap = favoriteIconDefaultBitmap;
3240 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3243 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3244 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3245 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3247 // Get a full cursor from `domainsDatabaseHelper`.
3248 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3250 // Initialize `domainSettingsSet`.
3251 Set<String> domainSettingsSet = new HashSet<>();
3253 // Get the domain name column index.
3254 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3256 // Populate `domainSettingsSet`.
3257 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3258 // Move `domainsCursor` to the current row.
3259 domainNameCursor.moveToPosition(i);
3261 // Store the domain name in `domainSettingsSet`.
3262 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3265 // Close `domainNameCursor.
3266 domainNameCursor.close();
3268 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3269 domainSettingsApplied = false;
3270 String domainNameInDatabase = null;
3272 // Check the hostname.
3273 if (domainSettingsSet.contains(hostName)) {
3274 domainSettingsApplied = true;
3275 domainNameInDatabase = hostName;
3278 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3279 if (hostName != null) {
3280 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3281 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3282 domainSettingsApplied = true;
3283 domainNameInDatabase = "*." + hostName;
3286 // Strip out the lowest subdomain of `host`.
3287 hostName = hostName.substring(hostName.indexOf(".") + 1);
3291 // Get a handle for the shared preference. `this` references the current context.
3292 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3294 // Store the general preference information.
3295 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3296 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3297 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3298 nightMode = sharedPreferences.getBoolean("night_mode", false);
3300 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3301 // Get a cursor for the current host and move it to the first position.
3302 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3303 currentHostDomainSettingsCursor.moveToFirst();
3305 // Get the settings from the cursor.
3306 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3307 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3308 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3309 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3310 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3311 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3312 easyListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYLIST)) == 1);
3313 easyPrivacyEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_EASYPRIVACY)) == 1);
3314 fanboysAnnoyanceListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_ANNOYANCE_LIST)) == 1);
3315 fanboysSocialBlockingListEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FANBOYS_SOCIAL_BLOCKING_LIST)) == 1);
3316 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3317 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3318 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3319 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3320 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3321 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3322 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3323 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3324 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3325 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3326 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3328 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3329 switch (nightModeInt) {
3330 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3334 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3339 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3341 javaScriptEnabled = true;
3344 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3345 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3346 pinnedDomainSslStartDate = null;
3348 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3351 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3352 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3353 pinnedDomainSslEndDate = null;
3355 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3358 // Close `currentHostDomainSettingsCursor`.
3359 currentHostDomainSettingsCursor.close();
3361 // Apply the domain settings.
3362 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3363 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3364 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3365 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3367 // Apply the font size.
3368 if (fontSize == 0) { // Apply the default font size.
3369 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3370 } else { // Apply the specified font size.
3371 mainWebView.getSettings().setTextZoom(fontSize);
3374 // Set third-party cookies status if API >= 21.
3375 if (Build.VERSION.SDK_INT >= 21) {
3376 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3379 // 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.
3380 // <https://redmine.stoutner.com/issues/160>
3381 if (!urlIsLoading) {
3382 switch (userAgentString) {
3383 case "System default user agent":
3384 // Set the user agent according to the system default.
3385 switch (defaultUserAgentString) {
3386 case "WebView default user agent":
3387 // Set the user agent to `""`, which uses the default value.
3388 mainWebView.getSettings().setUserAgentString("");
3391 case "Custom user agent":
3392 // Set the custom user agent.
3393 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3397 // Use the selected user agent.
3398 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3402 case "WebView default user agent":
3403 // Set the user agent to `""`, which uses the default value.
3404 mainWebView.getSettings().setUserAgentString("");
3408 // Use the selected user agent.
3409 mainWebView.getSettings().setUserAgentString(userAgentString);
3412 // Store the applied user agent string.
3413 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3416 // 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.
3418 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3420 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3422 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3423 // Store the values from `sharedPreferences` in variables.
3424 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3425 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3426 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3427 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3428 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3429 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
3430 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
3431 fanboysAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
3432 fanboysSocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
3434 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3436 javaScriptEnabled = true;
3439 // Apply the default settings.
3440 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3441 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3442 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3443 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3444 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3446 // Reset the pinned SSL certificate information.
3447 domainSettingsDatabaseId = -1;
3448 pinnedDomainSslCertificate = false;
3449 pinnedDomainSslIssuedToCNameString = "";
3450 pinnedDomainSslIssuedToONameString = "";
3451 pinnedDomainSslIssuedToUNameString = "";
3452 pinnedDomainSslIssuedByCNameString = "";
3453 pinnedDomainSslIssuedByONameString = "";
3454 pinnedDomainSslIssuedByUNameString = "";
3455 pinnedDomainSslStartDate = null;
3456 pinnedDomainSslEndDate = null;
3458 // Set third-party cookies status if API >= 21.
3459 if (Build.VERSION.SDK_INT >= 21) {
3460 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3463 // 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.
3464 // <https://redmine.stoutner.com/issues/160>
3465 if (!urlIsLoading) {
3466 switch (defaultUserAgentString) {
3467 case "WebView default user agent":
3468 // Set the user agent to `""`, which uses the default value.
3469 mainWebView.getSettings().setUserAgentString("");
3472 case "Custom user agent":
3473 // Set the custom user agent.
3474 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3478 // Use the selected user agent.
3479 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3482 // Store the applied user agent string.
3483 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3486 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3487 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3490 // Close `domainsDatabaseHelper`.
3491 domainsDatabaseHelper.close();
3493 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3494 onTheFlyDisplayImagesSet = false;
3495 setDisplayWebpageImages();
3497 // Update the privacy icons, but only if `mainMenu` has already been populated.
3498 if (mainMenu != null) {
3499 updatePrivacyIcons(true);
3504 private void setDisplayWebpageImages() {
3505 if (!onTheFlyDisplayImagesSet) {
3506 if (domainSettingsApplied) { // Custom domain settings are applied.
3507 switch (displayWebpageImagesInt) {
3508 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3509 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3512 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3513 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3516 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3517 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3520 } else { // Default settings are applied.
3521 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3526 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3527 // Get handles for the icons.
3528 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3529 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3530 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3531 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3533 // Update `privacyIcon`.
3534 if (javaScriptEnabled) { // JavaScript is enabled.
3535 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3536 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3537 privacyIconMenuItem.setIcon(R.drawable.warning);
3538 } else { // All the dangerous features are disabled.
3539 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3542 // Update `firstPartyCookiesIcon`.
3543 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3544 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3545 } else { // First-party cookies are disabled.
3547 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3549 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3553 // Update `domStorageIcon`.
3554 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3555 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3556 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3558 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3560 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3562 } else { // JavaScript is disabled, so DOM storage is ghosted.
3564 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3566 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3570 // Update `formDataIcon`.
3571 if (saveFormDataEnabled) { // Form data is enabled.
3572 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3573 } else { // Form data is disabled.
3575 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3577 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3581 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3582 if (runInvalidateOptionsMenu) {
3583 invalidateOptionsMenu();
3587 private void highlightUrlText() {
3588 String urlString = urlTextBox.getText().toString();
3590 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3591 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3592 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3593 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3596 // Get the index of the `/` immediately after the domain name.
3597 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3599 // De-emphasize the text after the domain name.
3600 if (endOfDomainName > 0) {
3601 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3605 private void loadBookmarksFolder() {
3606 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3607 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3609 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3610 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3612 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3613 // Inflate the individual item layout. `false` does not attach it to the root.
3614 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3618 public void bindView(View view, Context context, Cursor cursor) {
3619 // Get handles for the views.
3620 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3621 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3623 // Get the favorite icon byte array from the `Cursor`.
3624 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3626 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3627 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3629 // Display the bitmap in `bookmarkFavoriteIcon`.
3630 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3632 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3633 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3634 bookmarkNameTextView.setText(bookmarkNameString);
3636 // Make the font bold for folders.
3637 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3638 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3639 } else { // Reset the font to default for normal bookmarks.
3640 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3645 // Populate the `ListView` with the adapter.
3646 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3648 // Set the bookmarks drawer title.
3649 if (currentBookmarksFolder.isEmpty()) {
3650 bookmarksTitleTextView.setText(R.string.bookmarks);
3652 bookmarksTitleTextView.setText(currentBookmarksFolder);