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.annotation.SuppressLint;
25 import android.app.DialogFragment;
26 import android.app.DownloadManager;
27 import android.content.BroadcastReceiver;
28 import android.content.ClipData;
29 import android.content.ClipboardManager;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.SharedPreferences;
34 import android.content.res.Configuration;
35 import android.database.Cursor;
36 import android.graphics.Bitmap;
37 import android.graphics.BitmapFactory;
38 import android.graphics.Typeface;
39 import android.graphics.drawable.BitmapDrawable;
40 import android.graphics.drawable.Drawable;
41 import android.net.Uri;
42 import android.net.http.SslCertificate;
43 import android.net.http.SslError;
44 import android.os.Build;
45 import android.os.Bundle;
46 import android.os.Handler;
47 import android.preference.PreferenceManager;
48 import android.print.PrintDocumentAdapter;
49 import android.print.PrintManager;
50 import android.support.annotation.NonNull;
51 import android.support.design.widget.CoordinatorLayout;
52 import android.support.design.widget.FloatingActionButton;
53 import android.support.design.widget.NavigationView;
54 import android.support.design.widget.Snackbar;
55 import android.support.v4.app.ActivityCompat;
56 import android.support.v4.content.ContextCompat;
57 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
58 import android.support.v4.content.pm.ShortcutInfoCompat;
59 import android.support.v4.content.pm.ShortcutManagerCompat;
60 import android.support.v4.graphics.drawable.IconCompat;
61 import android.support.v4.view.GravityCompat;
62 import android.support.v4.widget.DrawerLayout;
63 import android.support.v4.widget.SwipeRefreshLayout;
64 import android.support.v7.app.ActionBar;
65 import android.support.v7.app.ActionBarDrawerToggle;
66 import android.support.v7.app.AppCompatActivity;
67 import android.support.v7.app.AppCompatDialogFragment;
68 import android.support.v7.widget.Toolbar;
69 import android.text.Editable;
70 import android.text.Spanned;
71 import android.text.TextWatcher;
72 import android.text.style.ForegroundColorSpan;
73 import android.util.Log;
74 import android.util.Patterns;
75 import android.view.ContextMenu;
76 import android.view.GestureDetector;
77 import android.view.KeyEvent;
78 import android.view.Menu;
79 import android.view.MenuItem;
80 import android.view.MotionEvent;
81 import android.view.View;
82 import android.view.ViewGroup;
83 import android.view.WindowManager;
84 import android.view.inputmethod.InputMethodManager;
85 import android.webkit.CookieManager;
86 import android.webkit.HttpAuthHandler;
87 import android.webkit.SslErrorHandler;
88 import android.webkit.WebBackForwardList;
89 import android.webkit.WebChromeClient;
90 import android.webkit.WebResourceResponse;
91 import android.webkit.WebStorage;
92 import android.webkit.WebView;
93 import android.webkit.WebViewClient;
94 import android.webkit.WebViewDatabase;
95 import android.widget.CursorAdapter;
96 import android.widget.EditText;
97 import android.widget.FrameLayout;
98 import android.widget.ImageView;
99 import android.widget.LinearLayout;
100 import android.widget.ListView;
101 import android.widget.ProgressBar;
102 import android.widget.RadioButton;
103 import android.widget.RelativeLayout;
104 import android.widget.TextView;
106 import com.stoutner.privacybrowser.BannerAd;
107 import com.stoutner.privacybrowser.BuildConfig;
108 import com.stoutner.privacybrowser.R;
109 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
110 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
111 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
112 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
113 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
114 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
115 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
116 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
117 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
118 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
119 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
120 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
121 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
122 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
123 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
124 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
126 import java.io.BufferedReader;
127 import java.io.ByteArrayInputStream;
128 import java.io.ByteArrayOutputStream;
130 import java.io.IOException;
131 import java.io.InputStreamReader;
132 import java.io.UnsupportedEncodingException;
133 import java.net.MalformedURLException;
135 import java.net.URLDecoder;
136 import java.net.URLEncoder;
137 import java.util.Date;
138 import java.util.HashMap;
139 import java.util.HashSet;
140 import java.util.Map;
141 import java.util.Set;
143 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
144 public class MainWebViewActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener, CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
145 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener,
146 NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
148 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`,
149 // `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`,
150 // `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`, and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
151 public static boolean darkTheme;
153 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`,
154 // `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`,
155 // `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
156 public static Bitmap favoriteIconBitmap;
158 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
159 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
160 public static String formattedUrlString;
162 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
163 public static SslCertificate sslCertificate;
165 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
166 public static String orbotStatus;
168 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
169 public static String webViewTitle;
171 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
172 public static String appliedUserAgentString;
174 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
175 public static boolean displayWebpageImagesBoolean;
177 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
178 public static boolean reloadOnRestart;
180 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
181 public static boolean loadUrlOnRestart;
183 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
184 public static boolean restartFromBookmarksActivity;
186 // `easyListVersion` is public static so it can be accessed from `AboutTabFragment`. It is also used in `onCreate()`.
187 public static String easyListVersion;
189 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and
190 // `loadBookmarksFolder()`.
191 public static String currentBookmarksFolder;
193 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
194 public static int domainSettingsDatabaseId;
196 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
197 public static String pinnedDomainSslIssuedToCNameString;
198 public static String pinnedDomainSslIssuedToONameString;
199 public static String pinnedDomainSslIssuedToUNameString;
200 public static String pinnedDomainSslIssuedByCNameString;
201 public static String pinnedDomainSslIssuedByONameString;
202 public static String pinnedDomainSslIssuedByUNameString;
203 public static Date pinnedDomainSslStartDate;
204 public static Date pinnedDomainSslEndDate;
207 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
208 private ActionBar appBar;
210 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
211 private boolean navigatingHistory;
213 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
214 private Bitmap favoriteIconDefaultBitmap;
216 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
217 private DrawerLayout drawerLayout;
219 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
220 private CoordinatorLayout rootCoordinatorLayout;
222 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
223 // `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
224 private WebView mainWebView;
226 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
227 private FrameLayout fullScreenVideoFrameLayout;
229 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
230 private SwipeRefreshLayout swipeRefreshLayout;
232 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
233 private RelativeLayout urlAppBarRelativeLayout;
235 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
236 private ImageView favoriteIconImageView;
238 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
239 private CookieManager cookieManager;
241 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
242 private final Map<String, String> customHeaders = new HashMap<>();
244 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
245 private boolean javaScriptEnabled;
247 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
248 private boolean firstPartyCookiesEnabled;
250 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
251 private boolean thirdPartyCookiesEnabled;
253 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
254 private boolean domStorageEnabled;
256 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
257 private boolean saveFormDataEnabled;
259 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
260 private boolean nightMode;
262 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
263 private boolean swipeToRefreshEnabled;
265 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
266 private String homepage;
268 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
269 private String searchURL;
271 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
272 private boolean adBlockerEnabled;
274 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
275 private Runtime privacyBrowserRuntime;
277 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
278 private boolean incognitoModeEnabled;
280 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
281 private boolean fullScreenBrowsingModeEnabled;
283 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
284 private boolean inFullScreenBrowsingMode;
286 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
287 private boolean hideSystemBarsOnFullscreen;
289 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
290 private boolean translucentNavigationBarOnFullscreen;
292 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
293 private boolean reapplyDomainSettingsOnRestart;
295 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
296 private String currentDomainName;
298 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
299 private boolean ignorePinnedSslCertificate;
301 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
302 private boolean waitingForOrbot;
304 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
305 private boolean domainSettingsApplied;
307 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
308 private int displayWebpageImagesInt;
310 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
311 private boolean onTheFlyDisplayImagesSet;
313 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
314 private String waitingForOrbotHTMLString;
316 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
317 private String privateDataDirectoryString;
319 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
320 private LinearLayout findOnPageLinearLayout;
322 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
323 private EditText findOnPageEditText;
325 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
326 private Menu mainMenu;
328 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
329 private ActionBarDrawerToggle drawerToggle;
331 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
332 private Toolbar supportAppBar;
334 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
335 private EditText urlTextBox;
337 // The color spans are used in `onCreate()` and `highlightUrlText()`.
338 private ForegroundColorSpan redColorSpan;
339 private ForegroundColorSpan initialGrayColorSpan;
340 private ForegroundColorSpan finalGrayColorSpan;
342 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
345 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
346 private SslErrorHandler sslErrorHandler;
348 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
349 private static HttpAuthHandler httpAuthHandler;
351 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
352 private InputMethodManager inputMethodManager;
354 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
355 private RelativeLayout mainWebViewRelativeLayout;
357 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
358 private boolean urlIsLoading;
360 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
361 private boolean pinnedDomainSslCertificate;
363 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
364 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
366 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
367 private ListView bookmarksListView;
369 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
370 private TextView bookmarksTitleTextView;
372 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
373 private Cursor bookmarksCursor;
375 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
376 private CursorAdapter bookmarksCursorAdapter;
378 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
379 private String oldFolderNameString;
382 // 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.
383 @SuppressLint({"SetJavaScriptEnabled"})
384 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
385 @SuppressWarnings("deprecation")
386 protected void onCreate(Bundle savedInstanceState) {
387 // Get a handle for `sharedPreferences`. `this` references the current context.
388 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
390 // Get the theme preference.
391 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
393 // Set the activity theme.
395 setTheme(R.style.PrivacyBrowserDark);
397 setTheme(R.style.PrivacyBrowserLight);
400 // Run the default commands.
401 super.onCreate(savedInstanceState);
403 // **DEBUG** Log the beginning of the loading of the ad blocker.
404 Log.i("AdBlocker", "Begin loading ad blocker");
406 // Initialize `adServerSet`.
407 final Set<String> adServersSet = new HashSet<>();
409 // Load the list of ad servers into memory.
411 // Load `easylist.txt` into a `BufferedReader`.
412 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("easylist.txt")));
414 // Create a string for storing each ad server.
415 String adBlockerEntry;
417 // Populate `adServersSet`.
418 while ((adBlockerEntry = bufferedReader.readLine()) != null) {
419 //noinspection StatementWithEmptyBody
420 if (adBlockerEntry.contains("##") || adBlockerEntry.contains("#?#") || adBlockerEntry.contains("#@#") || adBlockerEntry.startsWith("[")) {
421 // Entries that contain `##`, `#?#`, and `#@#` are for hiding elements in the main page's HTML. Entries that start with `[` describe the AdBlock compatibility level.
423 // Do nothing. Privacy Browser does not currently use these entries.
425 // **DEBUG** Log the entries that are not added.
426 // Log.i("AdBlocker", "Not added: " + adBlockerEntry);
427 } else if (adBlockerEntry.startsWith("!")){ // Entries that begin with `!` are comments.
428 if (adBlockerEntry.startsWith("! Version:")) {
429 // Store the EasyList version number.
430 easyListVersion = adBlockerEntry.substring(11);
433 // **DEBUG** Log the entries that are not added.
434 // Log.i("AdBlocker", "Not added: " + adBlockerEntry);
436 adServersSet.add(adBlockerEntry);
440 // Close `bufferedReader`.
441 bufferedReader.close();
442 } catch (IOException e) {
443 // The asset exists, so the `IOException` will never be thrown.
446 // **DEBUG** Log the finishing of the loading of the ad blocker.
447 Log.i("AdBlocker", "Finish loading ad blocker");
449 // Set the content view.
450 setContentView(R.layout.main_drawerlayout);
452 // Get a handle for `inputMethodManager`.
453 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
455 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
456 supportAppBar = findViewById(R.id.app_bar);
457 setSupportActionBar(supportAppBar);
458 appBar = getSupportActionBar();
460 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
461 assert appBar != null;
463 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
464 appBar.setCustomView(R.layout.url_app_bar);
465 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
467 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
468 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
469 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
470 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
472 // Get a handle for `urlTextBox`.
473 urlTextBox = findViewById(R.id.url_edittext);
475 // Remove the formatting from `urlTextBar` when the user is editing the text.
476 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
477 if (hasFocus) { // The user is editing `urlTextBox`.
478 // Remove the highlighting.
479 urlTextBox.getText().removeSpan(redColorSpan);
480 urlTextBox.getText().removeSpan(initialGrayColorSpan);
481 urlTextBox.getText().removeSpan(finalGrayColorSpan);
482 } else { // The user has stopped editing `urlTextBox`.
483 // Reapply the highlighting.
488 // Set the go button on the keyboard to load the URL in `urlTextBox`.
489 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
490 // If the event is a key-down event on the `enter` button, load the URL.
491 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
492 // Load the URL into the mainWebView and consume the event.
494 loadUrlFromTextBox();
495 } catch (UnsupportedEncodingException e) {
498 // If the enter key was pressed, consume the event.
501 // If any other key was pressed, do not consume the event.
506 // Set `waitingForOrbotHTMLString`.
507 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
509 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
510 currentDomainName = "";
511 orbotStatus = "unknown";
512 waitingForOrbot = false;
514 // Create an Orbot status `BroadcastReceiver`.
515 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
517 public void onReceive(Context context, Intent intent) {
518 // Store the content of the status message in `orbotStatus`.
519 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
521 // If we are waiting on Orbot, load the website now that Orbot is connected.
522 if (orbotStatus.equals("ON") && waitingForOrbot) {
523 // Reset `waitingForOrbot`.
524 waitingForOrbot = false;
526 // Load `formattedUrlString
527 loadUrl(formattedUrlString);
532 // Register `orbotStatusBroadcastReceiver` on `this` context.
533 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
535 // Get handles for views that need to be accessed.
536 drawerLayout = findViewById(R.id.drawerlayout);
537 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
538 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
539 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
540 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
541 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
542 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
543 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
544 mainWebView = findViewById(R.id.main_webview);
545 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
546 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
547 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
548 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
549 favoriteIconImageView = findViewById(R.id.favorite_icon);
551 // 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.
553 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
554 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
555 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
556 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
558 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
559 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
560 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
561 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
564 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
565 launchBookmarksActivityFab.setOnClickListener(v -> {
566 // Create an intent to launch the bookmarks activity.
567 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
569 // Include the current folder with the `Intent`.
570 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
573 startActivity(bookmarksIntent);
576 // Set the create new bookmark folder FAB to display the `AlertDialog`.
577 createBookmarkFolderFab.setOnClickListener(v -> {
578 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
579 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
580 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
583 // Set the create new bookmark FAB to display the `AlertDialog`.
584 createBookmarkFab.setOnClickListener(view -> {
585 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
586 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
587 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
590 // Create a double-tap listener to toggle full-screen mode.
591 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
592 // Override `onDoubleTap()`. All other events are handled using the default settings.
594 public boolean onDoubleTap(MotionEvent event) {
595 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
596 // Toggle `inFullScreenBrowsingMode`.
597 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
599 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
600 // Hide the `appBar`.
603 // Hide the `BannerAd` in the free flavor.
604 if (BuildConfig.FLAVOR.contentEquals("free")) {
605 BannerAd.hideAd(adView);
608 // Modify the system bars.
609 if (hideSystemBarsOnFullscreen) { // Hide everything.
610 // Remove the translucent overlays.
611 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
613 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
614 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
616 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
617 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
618 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
620 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
622 // Set `rootCoordinatorLayout` to fill the whole screen.
623 rootCoordinatorLayout.setFitsSystemWindows(false);
624 } else { // Hide everything except the status and navigation bars.
625 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
626 rootCoordinatorLayout.setFitsSystemWindows(false);
628 if (translucentNavigationBarOnFullscreen) { // 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.
629 // Set the navigation bar to be translucent.
630 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
633 } else { // Switch to normal viewing mode.
634 // Show the `appBar`.
637 // Show the `BannerAd` in the free flavor.
638 if (BuildConfig.FLAVOR.contentEquals("free")) {
639 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
640 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
642 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
643 adView = findViewById(R.id.adview);
646 // Remove the translucent navigation bar flag if it is set.
647 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
649 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
650 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
652 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
653 rootCoordinatorLayout.setSystemUiVisibility(0);
655 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
656 rootCoordinatorLayout.setFitsSystemWindows(true);
659 // Consume the double-tap.
661 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
667 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
668 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
669 // Call `performClick()` on the view, which is required for accessibility.
672 // Send the `event` to `gestureDetector`.
673 return gestureDetector.onTouchEvent(event);
676 // Update `findOnPageCountTextView`.
677 mainWebView.setFindListener(new WebView.FindListener() {
678 // Get a handle for `findOnPageCountTextView`.
679 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
682 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
683 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
684 // Set `findOnPageCountTextView` to `0/0`.
685 findOnPageCountTextView.setText(R.string.zero_of_zero);
686 } else if (isDoneCounting) { // There are matches.
687 // `activeMatchOrdinal` is zero-based.
688 int activeMatch = activeMatchOrdinal + 1;
690 // Build the match string.
691 String matchString = activeMatch + "/" + numberOfMatches;
693 // Set `findOnPageCountTextView`.
694 findOnPageCountTextView.setText(matchString);
699 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
700 findOnPageEditText.addTextChangedListener(new TextWatcher() {
702 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
707 public void onTextChanged(CharSequence s, int start, int before, int count) {
712 public void afterTextChanged(Editable s) {
713 // Search for the text in `mainWebView`.
714 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
718 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
719 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
720 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
721 // Hide the soft keyboard. `0` indicates no additional flags.
722 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
724 // Consume the event.
726 } else { // A different key was pressed.
727 // Do not consume the event.
732 // Implement swipe to refresh
733 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
734 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
735 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
737 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
738 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
739 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
741 // Listen for touches on the navigation menu.
742 final NavigationView navigationView = findViewById(R.id.navigationview);
743 navigationView.setNavigationItemSelectedListener(this);
745 // 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.
746 final Menu navigationMenu = navigationView.getMenu();
747 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
748 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
749 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
751 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
752 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
753 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
755 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
756 currentBookmarksFolder = "";
758 // Load the home folder, which is `""` in the database.
759 loadBookmarksFolder();
761 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
762 // Convert the id from long to int to match the format of the bookmarks database.
763 int databaseID = (int) id;
765 // Get the bookmark `Cursor` for this ID and move it to the first row.
766 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
767 bookmarkCursor.moveToFirst();
769 // Act upon the bookmark according to the type.
770 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
771 // Store the new folder name in `currentBookmarksFolder`.
772 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
774 // Load the new folder.
775 loadBookmarksFolder();
776 } else { // The selected bookmark is not a folder.
777 // Load the bookmark URL.
778 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
780 // Close the bookmarks drawer.
781 drawerLayout.closeDrawer(GravityCompat.END);
784 // Close the `Cursor`.
785 bookmarkCursor.close();
788 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
789 // Convert the database ID from `long` to `int`.
790 int databaseId = (int) id;
792 // Find out if the selected bookmark is a folder.
793 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
796 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
797 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
799 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
800 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
801 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
803 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
804 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
805 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
808 // Consume the event.
812 // The `DrawerListener` allows us to update the Navigation Menu.
813 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
815 public void onDrawerSlide(View drawerView, float slideOffset) {
819 public void onDrawerOpened(View drawerView) {
823 public void onDrawerClosed(View drawerView) {
827 public void onDrawerStateChanged(int newState) {
828 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
829 // Update the `Back`, `Forward`, and `History` menu items.
830 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
831 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
832 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
834 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
835 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
837 // Clear the focus from `urlTextBox` if it has it.
838 urlTextBox.clearFocus();
843 // drawerToggle creates the hamburger icon at the start of the AppBar.
844 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
846 mainWebView.setWebViewClient(new WebViewClient() {
847 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
848 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
849 @SuppressWarnings("deprecation")
851 public boolean shouldOverrideUrlLoading(WebView view, String url) {
852 if (url.startsWith("mailto:")) { // Load the email address in an external email program.
853 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
854 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
856 // Parse the url and set it as the data for the `Intent`.
857 emailIntent.setData(Uri.parse(url));
859 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
860 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
863 startActivity(emailIntent);
865 // Returning `true` indicates the application is handling the URL.
867 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
868 // `ACTION_DIAL` open the dialer and loads the phone number, but waits for the user to place the call.
869 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
871 // Add the phone number to the intent.
872 dialIntent.setData(Uri.parse(url));
874 // `FLAG_ACTIVITY_NEW_TASK` opens the dialer in a new task instead as part of Privacy Browser.
875 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
878 startActivity(dialIntent);
880 // Returning `true` indicates the application is handling the URL.
882 } else { // Load the URL in Privacy Browser.
883 // Apply the domain settings for the new URL.
884 applyDomainSettings(url);
886 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
891 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
892 @SuppressWarnings("deprecation")
894 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
895 if (adBlockerEnabled) { // Block ads.
896 // Extract the host from `url`.
897 Uri requestUri = Uri.parse(url);
898 String requestHost = requestUri.getHost();
900 // Initialize a variable to track if this is an ad server.
901 boolean requestHostIsAdServer = false;
903 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
904 if (requestHost != null) {
905 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
906 if (adServersSet.contains(requestHost)) {
907 requestHostIsAdServer = true;
910 // Strip out the lowest subdomain of `requestHost`.
911 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
915 if (requestHostIsAdServer) { // It is an ad server.
916 // Return an empty `WebResourceResponse`.
917 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
918 } else { // It is not an ad server.
919 // `return null` loads the requested resource.
922 } else { // Ad blocking is disabled.
923 // `return null` loads the requested resource.
928 // Handle HTTP authentication requests.
930 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
931 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
932 httpAuthHandler = handler;
934 // Display the HTTP authentication dialog.
935 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
936 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
939 // Update the URL in urlTextBox when the page starts to load.
941 public void onPageStarted(WebView view, String url, Bitmap favicon) {
942 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
944 mainWebView.setVisibility(View.INVISIBLE);
947 // Hide the keyboard. `0` indicates no additional flags.
948 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
950 // Check to see if we are waiting on Orbot.
951 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
952 // 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.
953 formattedUrlString = url;
955 // Display the formatted URL text.
956 urlTextBox.setText(formattedUrlString);
958 // Apply text highlighting to `urlTextBox`.
961 // Apply any custom domain settings if the URL was loaded by navigating history.
962 if (navigatingHistory) {
963 applyDomainSettings(url);
966 // 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.
971 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
973 public void onPageFinished(WebView view, String url) {
974 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
975 urlIsLoading = false;
977 // Clear the cache and history if Incognito Mode is enabled.
978 if (incognitoModeEnabled) {
979 // Clear the cache. `true` includes disk files.
980 mainWebView.clearCache(true);
982 // Clear the back/forward history.
983 mainWebView.clearHistory();
985 // Manually delete cache folders.
987 // Delete the main `cache` folder.
988 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
990 // Delete the `app_webview` folder, which contains an additional `WebView` cache. See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
991 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
992 } catch (IOException e) {
993 // Do nothing if an error is thrown.
997 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
998 if (!waitingForOrbot) {
999 // Check to see if `WebView` has set `url` to be `about:blank`.
1000 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1001 // Set `formattedUrlString` to `""`.
1002 formattedUrlString = "";
1004 urlTextBox.setText(formattedUrlString);
1006 // Request focus for `urlTextBox`.
1007 urlTextBox.requestFocus();
1009 // Display the keyboard.
1010 inputMethodManager.showSoftInput(urlTextBox, 0);
1012 // Apply the domain settings. This clears any settings from the previous domain.
1013 applyDomainSettings(formattedUrlString);
1014 } else { // `WebView` has loaded a webpage.
1015 // Set `formattedUrlString`.
1016 formattedUrlString = url;
1018 // Only update `urlTextBox` if the user is not typing in it.
1019 if (!urlTextBox.hasFocus()) {
1020 // Display the formatted URL text.
1021 urlTextBox.setText(formattedUrlString);
1023 // Apply text highlighting to `urlTextBox`.
1028 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1029 sslCertificate = mainWebView.getCertificate();
1031 // 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.
1032 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1033 // Initialize the current SSL certificate variables.
1034 String currentWebsiteIssuedToCName = "";
1035 String currentWebsiteIssuedToOName = "";
1036 String currentWebsiteIssuedToUName = "";
1037 String currentWebsiteIssuedByCName = "";
1038 String currentWebsiteIssuedByOName = "";
1039 String currentWebsiteIssuedByUName = "";
1040 Date currentWebsiteSslStartDate = null;
1041 Date currentWebsiteSslEndDate = null;
1044 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1045 if (sslCertificate != null) {
1046 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1047 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1048 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1049 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1050 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1051 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1052 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1053 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1056 // 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`.
1057 String currentWebsiteSslStartDateString = "";
1058 String currentWebsiteSslEndDateString = "";
1059 String pinnedDomainSslStartDateString = "";
1060 String pinnedDomainSslEndDateString = "";
1062 // Convert the `Dates` to `Strings` if they are not `null`.
1063 if (currentWebsiteSslStartDate != null) {
1064 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1067 if (currentWebsiteSslEndDate != null) {
1068 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1071 if (pinnedDomainSslStartDate != null) {
1072 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1075 if (pinnedDomainSslEndDate != null) {
1076 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1079 // Check to see if the pinned SSL certificate matches the current website certificate.
1080 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) || !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) ||
1081 !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) || !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1082 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) { // The pinned SSL certificate doesn't match the current domain certificate.
1083 //Display the pinned SSL certificate mismatch `AlertDialog`.
1084 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1085 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1091 // Handle SSL Certificate errors.
1093 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1094 // Get the current website SSL certificate.
1095 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1097 // Extract the individual pieces of information from the current website SSL certificate.
1098 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1099 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1100 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1101 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1102 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1103 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1104 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1105 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1107 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1108 if (pinnedDomainSslCertificate &&
1109 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) && currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) &&
1110 currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) && currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1111 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) { // An SSL certificate is pinned and matches the current domain certificate.
1112 // Proceed to the website without displaying an error.
1114 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1115 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1116 sslErrorHandler = handler;
1118 // Display the SSL error `AlertDialog`.
1119 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1120 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1125 // Get a handle for the progress bar.
1126 final ProgressBar progressBar = findViewById(R.id.progress_bar);
1128 mainWebView.setWebChromeClient(new WebChromeClient() {
1129 // Update the progress bar when a page is loading.
1131 public void onProgressChanged(WebView view, int progress) {
1132 // Inject the night mode CSS if night mode is enabled.
1134 // `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 used by WordPress.
1135 // `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color. `border: none` removes all borders, which can also be used to underline text.
1136 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
1137 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '" +
1138 "* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important; text-shadow: none !important; border: none !important;}" +
1139 "a {color: #1565C0 !important;}" +
1140 "'; parent.appendChild(style)})()", value -> {
1141 // Initialize a `Handler` to display `mainWebView`.
1142 Handler displayWebViewHandler = new Handler();
1144 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
1145 Runnable displayWebViewRunnable = () -> {
1146 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
1147 if (progressBar.getVisibility() == View.GONE) {
1148 mainWebView.setVisibility(View.VISIBLE);
1152 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
1153 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
1157 // Update the progress bar.
1158 progressBar.setProgress(progress);
1160 // Set the visibility of the progress bar.
1161 if (progress < 100) {
1162 // Show the progress bar.
1163 progressBar.setVisibility(View.VISIBLE);
1165 // Hide the progress bar.
1166 progressBar.setVisibility(View.GONE);
1168 // Display `mainWebView` if night mode is disabled.
1169 // 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 currently enabled.
1171 mainWebView.setVisibility(View.VISIBLE);
1174 //Stop the `SwipeToRefresh` indicator if it is running
1175 swipeRefreshLayout.setRefreshing(false);
1179 // Set the favorite icon when it changes.
1181 public void onReceivedIcon(WebView view, Bitmap icon) {
1182 // Only update the favorite icon if the website has finished loading.
1183 if (progressBar.getVisibility() == View.GONE) {
1184 // Save a copy of the favorite icon.
1185 favoriteIconBitmap = icon;
1187 // Place the favorite icon in the appBar.
1188 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1192 // Save a copy of the title when it changes.
1194 public void onReceivedTitle(WebView view, String title) {
1195 // Save a copy of the title.
1196 webViewTitle = title;
1199 // Enter full screen video
1201 public void onShowCustomView(View view, CustomViewCallback callback) {
1202 // Pause the ad if this is the free flavor.
1203 if (BuildConfig.FLAVOR.contentEquals("free")) {
1204 BannerAd.pauseAd(adView);
1207 // Remove the translucent overlays.
1208 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1210 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1211 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1213 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1214 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1215 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1217 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1219 // Set `rootCoordinatorLayout` to fill the entire screen.
1220 rootCoordinatorLayout.setFitsSystemWindows(false);
1222 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1223 fullScreenVideoFrameLayout.addView(view);
1224 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1227 // Exit full screen video
1228 public void onHideCustomView() {
1229 // Hide `fullScreenVideoFrameLayout`.
1230 fullScreenVideoFrameLayout.removeAllViews();
1231 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1233 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1234 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1236 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1237 rootCoordinatorLayout.setFitsSystemWindows(true);
1239 // Show the ad if this is the free flavor.
1240 if (BuildConfig.FLAVOR.contentEquals("free")) {
1241 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1242 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1244 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1245 adView = findViewById(R.id.adview);
1250 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1251 registerForContextMenu(mainWebView);
1253 // Allow the downloading of files.
1254 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1255 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1256 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1257 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1260 // Allow pinch to zoom.
1261 mainWebView.getSettings().setBuiltInZoomControls(true);
1263 // Hide zoom controls.
1264 mainWebView.getSettings().setDisplayZoomControls(false);
1266 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1267 mainWebView.getSettings().setUseWideViewPort(true);
1269 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1270 mainWebView.getSettings().setLoadWithOverviewMode(true);
1272 // Explicitly disable geolocation.
1273 mainWebView.getSettings().setGeolocationEnabled(false);
1275 // Initialize cookieManager.
1276 cookieManager = CookieManager.getInstance();
1278 // 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).
1279 customHeaders.put("X-Requested-With", "");
1281 // 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.
1282 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1284 // Get the intent that started the app.
1285 final Intent launchingIntent = getIntent();
1287 // Extract the launching intent data as `launchingIntentUriData`.
1288 final Uri launchingIntentUriData = launchingIntent.getData();
1290 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1291 if (launchingIntentUriData != null) {
1292 formattedUrlString = launchingIntentUriData.toString();
1295 // Get a handle for the `Runtime`.
1296 privacyBrowserRuntime = Runtime.getRuntime();
1298 // Store the application's private data directory.
1299 privateDataDirectoryString = getApplicationInfo().dataDir; // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1301 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1302 inFullScreenBrowsingMode = false;
1304 // Initialize AdView for the free flavor.
1305 adView = findViewById(R.id.adview);
1307 // Initialize the privacy settings variables.
1308 javaScriptEnabled = false;
1309 firstPartyCookiesEnabled = false;
1310 thirdPartyCookiesEnabled = false;
1311 domStorageEnabled = false;
1312 saveFormDataEnabled = false;
1315 // Initialize `webViewTitle`.
1316 webViewTitle = getString(R.string.no_title);
1318 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1319 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1320 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1321 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1323 // If the favorite icon is null, load the default.
1324 if (favoriteIconBitmap == null) {
1325 favoriteIconBitmap = favoriteIconDefaultBitmap;
1328 // Apply the app settings from the shared preferences.
1331 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1332 if (!waitingForOrbot) {
1333 loadUrl(formattedUrlString);
1338 protected void onNewIntent(Intent intent) {
1339 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1342 if (intent.getData() != null) {
1343 // Get the intent data and convert it to a string.
1344 final Uri intentUriData = intent.getData();
1345 formattedUrlString = intentUriData.toString();
1348 // Close the navigation drawer if it is open.
1349 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1350 drawerLayout.closeDrawer(GravityCompat.START);
1353 // Load the website.
1354 loadUrl(formattedUrlString);
1356 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1357 mainWebView.requestFocus();
1361 public void onRestart() {
1362 // Run the default commands.
1365 // Apply the app settings, which may have been changed in `SettingsActivity`.
1368 // Apply the domain settings if returning from the Domains Activity.
1369 if (reapplyDomainSettingsOnRestart) {
1370 // Reset `reapplyDomainSettingsOnRestart`.
1371 reapplyDomainSettingsOnRestart = false;
1373 // Reapply the domain settings.
1374 applyDomainSettings(formattedUrlString);
1377 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1378 updatePrivacyIcons(true);
1380 // Set the display webpage images mode.
1381 setDisplayWebpageImages();
1383 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1384 if (reloadOnRestart) {
1385 // Reload `mainWebView`.
1386 mainWebView.reload();
1388 // Reset `reloadOnRestartBoolean`.
1389 reloadOnRestart = false;
1392 // Load the URL on restart to apply changes to night mode.
1393 if (loadUrlOnRestart) {
1394 // Load the current `formattedUrlString`.
1395 loadUrl(formattedUrlString);
1397 // Reset `loadUrlOnRestart.
1398 loadUrlOnRestart = false;
1402 if (restartFromBookmarksActivity) {
1403 // Close the bookmarks drawer.
1404 drawerLayout.closeDrawer(GravityCompat.END);
1406 // Reload the bookmarks drawer.
1407 loadBookmarksFolder();
1409 // Reset `restartFromBookmarksActivity`.
1410 restartFromBookmarksActivity = false;
1414 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1416 public void onResume() {
1417 // Run the default commands.
1420 // Resume JavaScript (if enabled).
1421 mainWebView.resumeTimers();
1423 // Resume `mainWebView`.
1424 mainWebView.onResume();
1426 // Resume the adView for the free flavor.
1427 if (BuildConfig.FLAVOR.contentEquals("free")) {
1428 BannerAd.resumeAd(adView);
1433 public void onPause() {
1434 // Pause `mainWebView`.
1435 mainWebView.onPause();
1437 // Stop all JavaScript.
1438 mainWebView.pauseTimers();
1440 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1441 if (BuildConfig.FLAVOR.contentEquals("free")) {
1442 BannerAd.pauseAd(adView);
1449 public boolean onCreateOptionsMenu(Menu menu) {
1450 // Inflate the menu; this adds items to the action bar if it is present.
1451 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1453 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1456 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1457 updatePrivacyIcons(false);
1459 // Get handles for the menu items.
1460 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1461 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1462 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1463 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1465 // Only display third-party cookies if SDK >= 21
1466 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1468 // Get the shared preference values. `this` references the current context.
1469 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1471 // Set the status of the additional app bar icons. The default is `false`.
1472 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1473 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1474 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1475 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1476 } else { //Do not display the additional icons.
1477 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1478 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1479 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1486 public boolean onPrepareOptionsMenu(Menu menu) {
1487 // Get handles for the menu items.
1488 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1489 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1490 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1491 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1492 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1493 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1494 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1495 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1496 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1497 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1498 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1499 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1501 // Set the text for the domain menu item.
1502 if (domainSettingsApplied) {
1503 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1505 addOrEditDomain.setTitle(R.string.add_domain_settings);
1508 // Set the status of the menu item checkboxes.
1509 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1510 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1511 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1512 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1513 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1515 // Enable third-party cookies if first-party cookies are enabled.
1516 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1518 // Enable `DOM Storage` if JavaScript is enabled.
1519 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1521 // Enable `Clear Cookies` if there are any.
1522 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1524 // Get a count of the number of files in the `Local Storage` directory.
1525 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1526 int localStorageDirectoryNumberOfFiles = 0;
1527 if (localStorageDirectory.exists()) {
1528 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1531 // Get a count of the number of files in the `IndexedDB` directory.
1532 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1533 int indexedDBDirectoryNumberOfFiles = 0;
1534 if (indexedDBDirectory.exists()) {
1535 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1538 // Enable `Clear DOM Storage` if there is any.
1539 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1541 // Enable `Clear Form Data` is there is any.
1542 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1543 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1545 // Enable `Clear Data` if any of the submenu items are enabled.
1546 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1548 // Initialize font size variables.
1549 int fontSize = mainWebView.getSettings().getTextZoom();
1550 String fontSizeTitle;
1551 MenuItem selectedFontSizeMenuItem;
1553 // Prepare the font size title and current size menu item.
1556 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1557 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1561 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1562 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1566 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1567 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1571 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1572 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1576 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1577 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1581 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1582 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1586 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1587 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1591 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1592 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1596 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1597 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1601 // Set the font size title and select the current size menu item.
1602 fontSizeMenuItem.setTitle(fontSizeTitle);
1603 selectedFontSizeMenuItem.setChecked(true);
1605 // Only show `Refresh` if `swipeToRefresh` is disabled.
1606 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1608 // Run all the other default commands.
1609 super.onPrepareOptionsMenu(menu);
1611 // Display the menu.
1616 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1617 @SuppressLint("SetJavaScriptEnabled")
1618 // removeAllCookies is deprecated, but it is required for API < 21.
1619 @SuppressWarnings("deprecation")
1620 public boolean onOptionsItemSelected(MenuItem menuItem) {
1621 // Get the selected menu item ID.
1622 int menuItemId = menuItem.getItemId();
1624 // Set the commands that relate to the menu entries.
1625 switch (menuItemId) {
1626 case R.id.add_or_edit_domain:
1627 if (domainSettingsApplied) { // Edit the current domain settings.
1628 // Reapply the domain settings on returning to `MainWebViewActivity`.
1629 reapplyDomainSettingsOnRestart = true;
1630 currentDomainName = "";
1632 // Create an intent to launch the domains activity.
1633 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1635 // Put extra information instructing the domains activity to directly load the current domain.
1636 domainsIntent.putExtra("LoadDomain", domainSettingsDatabaseId);
1639 startActivity(domainsIntent);
1640 } else { // Add a new domain.
1641 // Show the add domain `AlertDialog`.
1642 AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
1643 addDomainDialog.show(getSupportFragmentManager(), getResources().getString(R.string.add_domain));
1647 case R.id.toggle_javascript:
1648 // Switch the status of javaScriptEnabled.
1649 javaScriptEnabled = !javaScriptEnabled;
1651 // Apply the new JavaScript status.
1652 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1654 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1655 updatePrivacyIcons(true);
1657 // Display a `Snackbar`.
1658 if (javaScriptEnabled) { // JavaScrip is enabled.
1659 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1660 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1661 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1662 } else { // Privacy mode.
1663 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1666 // Reload the WebView.
1667 mainWebView.reload();
1670 case R.id.toggle_first_party_cookies:
1671 // Switch the status of firstPartyCookiesEnabled.
1672 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1674 // Update the menu checkbox.
1675 menuItem.setChecked(firstPartyCookiesEnabled);
1677 // Apply the new cookie status.
1678 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1680 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1681 updatePrivacyIcons(true);
1683 // Display a `Snackbar`.
1684 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1685 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1686 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1687 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1688 } else { // Privacy mode.
1689 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1692 // Reload the WebView.
1693 mainWebView.reload();
1696 case R.id.toggle_third_party_cookies:
1697 if (Build.VERSION.SDK_INT >= 21) {
1698 // Switch the status of thirdPartyCookiesEnabled.
1699 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1701 // Update the menu checkbox.
1702 menuItem.setChecked(thirdPartyCookiesEnabled);
1704 // Apply the new cookie status.
1705 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1707 // Display a `Snackbar`.
1708 if (thirdPartyCookiesEnabled) {
1709 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1711 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1714 // Reload the WebView.
1715 mainWebView.reload();
1716 } // Else do nothing because SDK < 21.
1719 case R.id.toggle_dom_storage:
1720 // Switch the status of domStorageEnabled.
1721 domStorageEnabled = !domStorageEnabled;
1723 // Update the menu checkbox.
1724 menuItem.setChecked(domStorageEnabled);
1726 // Apply the new DOM Storage status.
1727 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1729 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1730 updatePrivacyIcons(true);
1732 // Display a `Snackbar`.
1733 if (domStorageEnabled) {
1734 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1736 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1739 // Reload the WebView.
1740 mainWebView.reload();
1743 case R.id.toggle_save_form_data:
1744 // Switch the status of saveFormDataEnabled.
1745 saveFormDataEnabled = !saveFormDataEnabled;
1747 // Update the menu checkbox.
1748 menuItem.setChecked(saveFormDataEnabled);
1750 // Apply the new form data status.
1751 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1753 // Display a `Snackbar`.
1754 if (saveFormDataEnabled) {
1755 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1757 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1760 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1761 updatePrivacyIcons(true);
1763 // Reload the WebView.
1764 mainWebView.reload();
1767 case R.id.clear_cookies:
1768 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1769 .setAction(R.string.undo, v -> {
1770 // Do nothing because everything will be handled by `onDismissed()` below.
1772 .addCallback(new Snackbar.Callback() {
1774 public void onDismissed(Snackbar snackbar, int event) {
1776 // The user pushed the `Undo` button.
1777 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1781 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1783 // `cookieManager.removeAllCookie()` varies by SDK.
1784 if (Build.VERSION.SDK_INT < 21) {
1785 cookieManager.removeAllCookie();
1787 // `null` indicates no callback.
1788 cookieManager.removeAllCookies(null);
1796 case R.id.clear_dom_storage:
1797 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1798 .setAction(R.string.undo, v -> {
1799 // Do nothing because everything will be handled by `onDismissed()` below.
1801 .addCallback(new Snackbar.Callback() {
1803 public void onDismissed(Snackbar snackbar, int event) {
1805 // The user pushed the `Undo` button.
1806 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1810 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1812 // Delete the DOM Storage.
1813 WebStorage webStorage = WebStorage.getInstance();
1814 webStorage.deleteAllData();
1816 // Manually delete the DOM storage files and directories.
1818 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1819 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1821 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1822 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1823 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1824 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1825 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1826 } catch (IOException e) {
1827 // Do nothing if an error is thrown.
1835 case R.id.clear_form_data:
1836 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1837 .setAction(R.string.undo, v -> {
1838 // Do nothing because everything will be handled by `onDismissed()` below.
1840 .addCallback(new Snackbar.Callback() {
1842 public void onDismissed(Snackbar snackbar, int event) {
1844 // The user pushed the `Undo` button.
1845 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1849 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1851 // Delete the form data.
1852 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1853 mainWebViewDatabase.clearFormData();
1860 case R.id.font_size_twenty_five_percent:
1861 mainWebView.getSettings().setTextZoom(25);
1864 case R.id.font_size_fifty_percent:
1865 mainWebView.getSettings().setTextZoom(50);
1868 case R.id.font_size_seventy_five_percent:
1869 mainWebView.getSettings().setTextZoom(75);
1872 case R.id.font_size_one_hundred_percent:
1873 mainWebView.getSettings().setTextZoom(100);
1876 case R.id.font_size_one_hundred_twenty_five_percent:
1877 mainWebView.getSettings().setTextZoom(125);
1880 case R.id.font_size_one_hundred_fifty_percent:
1881 mainWebView.getSettings().setTextZoom(150);
1884 case R.id.font_size_one_hundred_seventy_five_percent:
1885 mainWebView.getSettings().setTextZoom(175);
1888 case R.id.font_size_two_hundred_percent:
1889 mainWebView.getSettings().setTextZoom(200);
1892 case R.id.display_images:
1893 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1894 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1895 mainWebView.reload();
1896 } else { // Images are not currently loaded automatically.
1897 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1900 // Set `onTheFlyDisplayImagesSet`.
1901 onTheFlyDisplayImagesSet = true;
1905 // Setup the share string.
1906 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1908 // Create the share intent.
1909 Intent shareIntent = new Intent();
1910 shareIntent.setAction(Intent.ACTION_SEND);
1911 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1912 shareIntent.setType("text/plain");
1915 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1918 case R.id.find_on_page:
1919 // Hide the URL app bar.
1920 supportAppBar.setVisibility(View.GONE);
1922 // Show the Find on Page `RelativeLayout`.
1923 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1925 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android. http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1926 findOnPageEditText.postDelayed(() -> {
1927 // Set the focus on `findOnPageEditText`.
1928 findOnPageEditText.requestFocus();
1930 // Display the keyboard. `0` sets no input flags.
1931 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1936 // Get a `PrintManager` instance.
1937 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1939 // Convert `mainWebView` to `printDocumentAdapter`.
1940 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1942 // Remove the lint error below that `printManager` might be `null`.
1943 assert printManager != null;
1945 // Print the document. The print attributes are `null`.
1946 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1949 case R.id.view_source:
1950 // Launch the Vew Source activity.
1951 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1952 startActivity(viewSourceIntent);
1955 case R.id.add_to_homescreen:
1956 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1957 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1958 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1960 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1964 mainWebView.reload();
1968 // Don't consume the event.
1969 return super.onOptionsItemSelected(menuItem);
1973 // removeAllCookies is deprecated, but it is required for API < 21.
1974 @SuppressWarnings("deprecation")
1976 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1977 int menuItemId = menuItem.getItemId();
1979 switch (menuItemId) {
1985 if (mainWebView.canGoBack()) {
1986 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1987 navigatingHistory = true;
1989 // Load the previous website in the history.
1990 mainWebView.goBack();
1995 if (mainWebView.canGoForward()) {
1996 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1997 navigatingHistory = true;
1999 // Load the next website in the history.
2000 mainWebView.goForward();
2005 // Get the `WebBackForwardList`.
2006 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2008 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2009 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2010 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2013 case R.id.downloads:
2014 // Launch the system Download Manager.
2015 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2017 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2018 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2020 startActivity(downloadManagerIntent);
2024 // Reapply the domain settings on returning to `MainWebViewActivity`.
2025 reapplyDomainSettingsOnRestart = true;
2026 currentDomainName = "";
2028 // Launch `DomainsActivity`.
2029 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2030 startActivity(domainsIntent);
2034 // Reapply the domain settings on returning to `MainWebViewActivity`.
2035 reapplyDomainSettingsOnRestart = true;
2036 currentDomainName = "";
2038 // Launch `SettingsActivity`.
2039 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2040 startActivity(settingsIntent);
2044 // Launch `GuideActivity`.
2045 Intent guideIntent = new Intent(this, GuideActivity.class);
2046 startActivity(guideIntent);
2050 // Launch `AboutActivity`.
2051 Intent aboutIntent = new Intent(this, AboutActivity.class);
2052 startActivity(aboutIntent);
2055 case R.id.clearAndExit:
2056 // Get a handle for `sharedPreferences`. `this` references the current context.
2057 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2059 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2062 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2063 // The command to remove cookies changed slightly in API 21.
2064 if (Build.VERSION.SDK_INT >= 21) {
2065 cookieManager.removeAllCookies(null);
2067 cookieManager.removeAllCookie();
2070 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2072 // We have to use two commands because `Runtime.exec()` does not like `*`.
2073 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2074 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2075 } catch (IOException e) {
2076 // Do nothing if an error is thrown.
2080 // Clear DOM storage.
2081 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2082 // Ask `WebStorage` to clear the DOM storage.
2083 WebStorage webStorage = WebStorage.getInstance();
2084 webStorage.deleteAllData();
2086 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2088 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2089 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2091 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2092 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2093 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2094 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2095 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2096 } catch (IOException e) {
2097 // Do nothing if an error is thrown.
2102 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2103 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2104 webViewDatabase.clearFormData();
2106 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2108 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2109 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2110 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2111 } catch (IOException e) {
2112 // Do nothing if an error is thrown.
2117 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2118 // `true` includes disk files.
2119 mainWebView.clearCache(true);
2121 // Manually delete the cache directories.
2123 // Delete the main cache directory.
2124 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2126 // Delete the secondary `Service Worker` cache directory. We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2127 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2128 } catch (IOException e) {
2129 // Do nothing if an error is thrown.
2133 // Clear SSL certificate preferences.
2134 mainWebView.clearSslPreferences();
2136 // Clear the back/forward history.
2137 mainWebView.clearHistory();
2139 // Clear `formattedUrlString`.
2140 formattedUrlString = null;
2142 // Clear `customHeaders`.
2143 customHeaders.clear();
2145 // Detach all views from `mainWebViewRelativeLayout`.
2146 mainWebViewRelativeLayout.removeAllViews();
2148 // Destroy the internal state of `mainWebView`.
2149 mainWebView.destroy();
2151 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2152 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2153 if (clearEverything) {
2155 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2156 } catch (IOException e) {
2157 // Do nothing if an error is thrown.
2161 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2162 if (Build.VERSION.SDK_INT >= 21) {
2163 finishAndRemoveTask();
2168 // Remove the terminated program from RAM. The status code is `0`.
2173 // Close the navigation drawer.
2174 drawerLayout.closeDrawer(GravityCompat.START);
2179 public void onPostCreate(Bundle savedInstanceState) {
2180 super.onPostCreate(savedInstanceState);
2182 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2183 drawerToggle.syncState();
2187 public void onConfigurationChanged(Configuration newConfig) {
2188 super.onConfigurationChanged(newConfig);
2190 // Reload the ad for the free flavor if we are not in full screen mode.
2191 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2193 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2195 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2196 adView = findViewById(R.id.adview);
2199 // `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: https://code.google.com/p/android/issues/detail?id=20493#c8
2200 // ActivityCompat.invalidateOptionsMenu(this);
2204 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2205 // Store the `HitTestResult`.
2206 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2209 final String imageUrl;
2210 final String linkUrl;
2212 // Get a handle for the `ClipboardManager`.
2213 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2215 // Remove the lint errors below that `clipboardManager` might be `null`.
2216 assert clipboardManager != null;
2218 switch (hitTestResult.getType()) {
2219 // `SRC_ANCHOR_TYPE` is a link.
2220 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2221 // Get the target URL.
2222 linkUrl = hitTestResult.getExtra();
2224 // Set the target URL as the title of the `ContextMenu`.
2225 menu.setHeaderTitle(linkUrl);
2227 // Add a `Load URL` entry.
2228 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
2233 // Add a `Copy URL` entry.
2234 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2235 // Save the link URL in a `ClipData`.
2236 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2238 // Set the `ClipData` as the clipboard's primary clip.
2239 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2243 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2244 menu.add(R.string.cancel);
2247 case WebView.HitTestResult.EMAIL_TYPE:
2248 // Get the target URL.
2249 linkUrl = hitTestResult.getExtra();
2251 // Set the target URL as the title of the `ContextMenu`.
2252 menu.setHeaderTitle(linkUrl);
2254 // Add a `Write Email` entry.
2255 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2256 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2257 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2259 // Parse the url and set it as the data for the `Intent`.
2260 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2262 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2263 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2266 startActivity(emailIntent);
2270 // Add a `Copy Email Address` entry.
2271 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2272 // Save the email address in a `ClipData`.
2273 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2275 // Set the `ClipData` as the clipboard's primary clip.
2276 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2280 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2281 menu.add(R.string.cancel);
2284 // `IMAGE_TYPE` is an image.
2285 case WebView.HitTestResult.IMAGE_TYPE:
2286 // Get the image URL.
2287 imageUrl = hitTestResult.getExtra();
2289 // Set the image URL as the title of the `ContextMenu`.
2290 menu.setHeaderTitle(imageUrl);
2292 // Add a `View Image` entry.
2293 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2298 // Add a `Download Image` entry.
2299 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2300 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2301 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2302 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2306 // Add a `Copy URL` entry.
2307 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2308 // Save the image URL in a `ClipData`.
2309 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2311 // Set the `ClipData` as the clipboard's primary clip.
2312 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2316 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2317 menu.add(R.string.cancel);
2321 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2322 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2323 // Get the image URL.
2324 imageUrl = hitTestResult.getExtra();
2326 // Set the image URL as the title of the `ContextMenu`.
2327 menu.setHeaderTitle(imageUrl);
2329 // Add a `View Image` entry.
2330 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2335 // Add a `Download Image` entry.
2336 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2337 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2338 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2339 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2343 // Add a `Copy URL` entry.
2344 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2345 // Save the image URL in a `ClipData`.
2346 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2348 // Set the `ClipData` as the clipboard's primary clip.
2349 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2353 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2354 menu.add(R.string.cancel);
2360 public void onAddDomain(AppCompatDialogFragment dialogFragment) {
2361 // Reapply the domain settings on returning to `MainWebViewActivity`.
2362 reapplyDomainSettingsOnRestart = true;
2363 currentDomainName = "";
2365 // Get the new domain name `String` from `dialogFragment`.
2366 EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
2367 String domainNameString = domainNameEditText.getText().toString();
2369 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2370 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2371 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2373 // Create the domain and store the database ID in `currentDomainDatabaseId`.
2374 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
2376 // Create an intent to launch the domains activity.
2377 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2379 // Put extra information instructing the domains activity to directly load the current domain.
2380 domainsIntent.putExtra("LoadDomain", newDomainDatabaseId);
2383 startActivity(domainsIntent);
2387 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2388 // Get the `EditTexts` from the `dialogFragment`.
2389 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2390 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2392 // Extract the strings from the `EditTexts`.
2393 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2394 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2396 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2397 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2398 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2399 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2401 // Display the new bookmark below the current items in the (0 indexed) list.
2402 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2404 // Create the bookmark.
2405 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2407 // Update `bookmarksCursor` with the current contents of this folder.
2408 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2410 // Update the `ListView`.
2411 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2413 // Scroll to the new bookmark.
2414 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2418 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2419 // Get handles for the views in `dialogFragment`.
2420 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2421 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2422 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2424 // Get new folder name string.
2425 String folderNameString = createFolderNameEditText.getText().toString();
2427 // Get the new folder icon `Bitmap`.
2428 Bitmap folderIconBitmap;
2429 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2430 // Get the default folder icon and convert it to a `Bitmap`.
2431 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2432 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2433 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2434 } else { // Use the `WebView` favorite icon.
2435 folderIconBitmap = favoriteIconBitmap;
2438 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2439 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2440 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2441 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2443 // Move all the bookmarks down one in the display order.
2444 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2445 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2446 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2449 // Create the folder, which will be placed at the top of the `ListView`.
2450 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2452 // Update `bookmarksCursor` with the current contents of this folder.
2453 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2455 // Update the `ListView`.
2456 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2458 // Scroll to the new folder.
2459 bookmarksListView.setSelection(0);
2463 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2464 // Get the shortcut name.
2465 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2466 String shortcutNameString = shortcutNameEditText.getText().toString();
2468 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2469 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2471 // Setup the shortcut intent.
2472 Intent shortcutIntent = new Intent();
2473 shortcutIntent.setAction(Intent.ACTION_VIEW);
2474 shortcutIntent.setData(Uri.parse(formattedUrlString));
2476 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2477 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2479 // Add the required fields to the shortcut info builder.
2480 shortcutInfoBuilder.setIcon(favoriteIcon);
2481 shortcutInfoBuilder.setIntent(shortcutIntent);
2482 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2484 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2485 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2489 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2490 // Download the image if it has an HTTP or HTTPS URI.
2491 if (imageUrl.startsWith("http")) {
2492 // Get a handle for the system `DOWNLOAD_SERVICE`.
2493 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2495 // Parse `imageUrl`.
2496 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2498 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2499 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2500 if (firstPartyCookiesEnabled) {
2501 // Get the cookies for `imageUrl`.
2502 String cookies = cookieManager.getCookie(imageUrl);
2504 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2505 downloadRequest.addRequestHeader("Cookie", cookies);
2508 // Get the file name from `dialogFragment`.
2509 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2510 String imageName = downloadImageNameEditText.getText().toString();
2512 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2513 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2514 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2515 } else { // Only set the title using `imageName`.
2516 downloadRequest.setTitle(imageName);
2519 // Allow `MediaScanner` to index the download if it is a media file.
2520 downloadRequest.allowScanningByMediaScanner();
2522 // Add the URL as the description for the download.
2523 downloadRequest.setDescription(imageUrl);
2525 // Show the download notification after the download is completed.
2526 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2528 // Remove the lint warning below that `downloadManager` might be `null`.
2529 assert downloadManager != null;
2531 // Initiate the download.
2532 downloadManager.enqueue(downloadRequest);
2533 } else { // The image is not an HTTP or HTTPS URI.
2534 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2539 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2540 // Download the file if it has an HTTP or HTTPS URI.
2541 if (downloadUrl.startsWith("http")) {
2543 // Get a handle for the system `DOWNLOAD_SERVICE`.
2544 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2546 // Parse `downloadUrl`.
2547 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2549 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2550 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2551 if (firstPartyCookiesEnabled) {
2552 // Get the cookies for `downloadUrl`.
2553 String cookies = cookieManager.getCookie(downloadUrl);
2555 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2556 downloadRequest.addRequestHeader("Cookie", cookies);
2559 // Get the file name from `dialogFragment`.
2560 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2561 String fileName = downloadFileNameEditText.getText().toString();
2563 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2564 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2565 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2566 } else { // Only set the title using `fileName`.
2567 downloadRequest.setTitle(fileName);
2570 // Allow `MediaScanner` to index the download if it is a media file.
2571 downloadRequest.allowScanningByMediaScanner();
2573 // Add the URL as the description for the download.
2574 downloadRequest.setDescription(downloadUrl);
2576 // Show the download notification after the download is completed.
2577 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2579 // Remove the lint warning below that `downloadManager` might be `null`.
2580 assert downloadManager != null;
2582 // Initiate the download.
2583 downloadManager.enqueue(downloadRequest);
2584 } else { // The download is not an HTTP or HTTPS URI.
2585 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2590 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2591 // Get handles for the views from `dialogFragment`.
2592 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2593 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2594 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2596 // Store the bookmark strings.
2597 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2598 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2600 // Update the bookmark.
2601 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2602 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2603 } else { // Update the bookmark using the `WebView` favorite icon.
2604 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2605 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2606 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2607 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2609 // Update the bookmark and the favorite icon.
2610 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2613 // Update `bookmarksCursor` with the current contents of this folder.
2614 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2616 // Update the `ListView`.
2617 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2621 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2622 // Get handles for the views from `dialogFragment`.
2623 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2624 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2625 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2626 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2628 // Get the new folder name.
2629 String newFolderNameString = editFolderNameEditText.getText().toString();
2631 // Check if the favorite icon has changed.
2632 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2633 // Update the name in the database.
2634 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2635 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2636 // Get the new folder icon `Bitmap`.
2637 Bitmap folderIconBitmap;
2638 if (defaultFolderIconRadioButton.isChecked()) {
2639 // Get the default folder icon and convert it to a `Bitmap`.
2640 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2641 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2642 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2643 } else { // Use the `WebView` favorite icon.
2644 folderIconBitmap = favoriteIconBitmap;
2647 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2648 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2649 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2650 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2652 // Update the folder icon in the database.
2653 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2654 } else { // The folder icon and the name have changed.
2655 // Get the new folder icon `Bitmap`.
2656 Bitmap folderIconBitmap;
2657 if (defaultFolderIconRadioButton.isChecked()) {
2658 // Get the default folder icon and convert it to a `Bitmap`.
2659 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2660 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2661 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2662 } else { // Use the `WebView` favorite icon.
2663 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2666 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2667 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2668 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2669 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2671 // Update the folder name and icon in the database.
2672 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2675 // Update `bookmarksCursor` with the current contents of this folder.
2676 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2678 // Update the `ListView`.
2679 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2683 public void onHttpAuthenticationCancel() {
2684 // Cancel the `HttpAuthHandler`.
2685 httpAuthHandler.cancel();
2689 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2690 // Get handles for the `EditTexts`.
2691 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2692 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2694 // Proceed with the HTTP authentication.
2695 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2698 public void viewSslCertificate(View view) {
2699 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2700 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2701 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2705 public void onSslErrorCancel() {
2706 sslErrorHandler.cancel();
2710 public void onSslErrorProceed() {
2711 sslErrorHandler.proceed();
2715 public void onSslMismatchBack() {
2716 if (mainWebView.canGoBack()) { // There is a back page in the history.
2717 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2718 navigatingHistory = true;
2721 mainWebView.goBack();
2722 } else { // There are no pages to go back to.
2723 // Load a blank page
2729 public void onSslMismatchProceed() {
2730 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2731 ignorePinnedSslCertificate = true;
2735 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2736 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2737 navigatingHistory = true;
2739 // Load the history entry.
2740 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2744 public void onClearHistory() {
2745 // Clear the history.
2746 mainWebView.clearHistory();
2749 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2751 public void onBackPressed() {
2752 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2753 // Close the navigation drawer.
2754 drawerLayout.closeDrawer(GravityCompat.START);
2755 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2756 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2757 // close the bookmarks drawer.
2758 drawerLayout.closeDrawer(GravityCompat.END);
2759 } else { // A subfolder is displayed.
2760 // Place the former parent folder in `currentFolder`.
2761 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2763 // Load the new folder.
2764 loadBookmarksFolder();
2767 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2768 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2769 navigatingHistory = true;
2772 mainWebView.goBack();
2773 } else { // There isn't anything to do in Privacy Browser.
2774 // Pass `onBackPressed()` to the system.
2775 super.onBackPressed();
2779 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2780 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2781 String unformattedUrlString = urlTextBox.getText().toString().trim();
2783 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2784 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2785 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2786 if (!unformattedUrlString.startsWith("http")) {
2787 unformattedUrlString = "http://" + unformattedUrlString;
2790 // Initialize `unformattedUrl`.
2791 URL unformattedUrl = null;
2793 // 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.
2795 unformattedUrl = new URL(unformattedUrlString);
2796 } catch (MalformedURLException e) {
2797 e.printStackTrace();
2800 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2801 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2802 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2803 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2804 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2805 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2808 Uri.Builder formattedUri = new Uri.Builder();
2809 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2811 // Decode `formattedUri` as a `String` in `UTF-8`.
2812 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2814 // Sanitize the search input and convert it to a search.
2815 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2817 // Add the base search URL.
2818 formattedUrlString = searchURL + encodedUrlString;
2821 loadUrl(formattedUrlString);
2825 private void loadUrl(String url) {
2826 // Apply any custom domain settings.
2827 applyDomainSettings(url);
2830 mainWebView.loadUrl(url, customHeaders);
2832 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2833 urlIsLoading = true;
2836 public void findPreviousOnPage(View view) {
2837 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2838 mainWebView.findNext(false);
2841 public void findNextOnPage(View view) {
2842 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2843 mainWebView.findNext(true);
2846 public void closeFindOnPage(View view) {
2847 // Delete the contents of `find_on_page_edittext`.
2848 findOnPageEditText.setText(null);
2850 // Clear the highlighted phrases.
2851 mainWebView.clearMatches();
2853 // Hide the Find on Page `RelativeLayout`.
2854 findOnPageLinearLayout.setVisibility(View.GONE);
2856 // Show the URL app bar.
2857 supportAppBar.setVisibility(View.VISIBLE);
2859 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2860 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2863 private void applyAppSettings() {
2864 // Get a handle for the shared preferences.
2865 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2867 // Store the values from the shared preferences in variables.
2868 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2869 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2870 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2871 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2872 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2873 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2874 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2875 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2876 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2877 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2878 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2879 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2880 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2881 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2882 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2884 // Set the homepage, search, and proxy options.
2885 if (proxyThroughOrbot) { // Set the Tor options.
2886 // Set `torHomepageString` as `homepage`.
2887 homepage = torHomepageString;
2889 // If formattedUrlString is null assign the homepage to it.
2890 if (formattedUrlString == null) {
2891 formattedUrlString = homepage;
2894 // Set the search URL.
2895 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2896 searchURL = torSearchCustomURLString;
2897 } else { // Use the string from the pre-built list.
2898 searchURL = torSearchString;
2901 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2902 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2904 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2906 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2908 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2911 // Display a message to the user if we are waiting on Orbot.
2912 if (!orbotStatus.equals("ON")) {
2913 // Set `waitingForOrbot`.
2914 waitingForOrbot = true;
2916 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2917 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2919 } else { // Set the non-Tor options.
2920 // Set `homepageString` as `homepage`.
2921 homepage = homepageString;
2923 // If formattedUrlString is null assign the homepage to it.
2924 if (formattedUrlString == null) {
2925 formattedUrlString = homepage;
2928 // Set the search URL.
2929 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2930 searchURL = searchCustomURLString;
2931 } else { // Use the string from the pre-built list.
2932 searchURL = searchString;
2935 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2936 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2938 // Set the default `appBar` background. `this` refers to the context.
2940 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2942 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2945 // Reset `waitingForOrbot.
2946 waitingForOrbot = false;
2949 // Set swipe to refresh.
2950 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2952 // Set Do Not Track status.
2953 if (doNotTrackEnabled) {
2954 customHeaders.put("DNT", "1");
2956 customHeaders.remove("DNT");
2959 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2960 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2961 if (hideSystemBarsOnFullscreen) { // Hide everything.
2962 // Remove the translucent navigation setting if it is currently flagged.
2963 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2965 // Remove the translucent status bar overlay.
2966 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2968 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2969 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2971 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2972 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2973 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2975 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2976 } else { // Hide everything except the status and navigation bars.
2977 // Add the translucent status flag if it is unset.
2978 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2980 if (translucentNavigationBarOnFullscreen) {
2981 // Set the navigation bar to be translucent.
2982 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2984 // Set the navigation bar to be black.
2985 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2988 } else { // Switch to normal viewing mode.
2989 // Reset `inFullScreenBrowsingMode` to `false`.
2990 inFullScreenBrowsingMode = false;
2992 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2993 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2997 // Show the `BannerAd` in the free flavor.
2998 if (BuildConfig.FLAVOR.contentEquals("free")) {
2999 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
3000 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
3002 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3003 adView = findViewById(R.id.adview);
3006 // Remove the translucent navigation bar flag if it is set.
3007 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3009 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3010 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3012 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3013 rootCoordinatorLayout.setSystemUiVisibility(0);
3015 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3016 rootCoordinatorLayout.setFitsSystemWindows(true);
3020 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3021 @SuppressWarnings("deprecation")
3022 private void applyDomainSettings(String url) {
3023 // Reset `navigatingHistory`.
3024 navigatingHistory = false;
3026 // Parse the URL into a URI.
3027 Uri uri = Uri.parse(url);
3029 // Extract the domain from `uri`.
3030 String hostName = uri.getHost();
3032 // Initialize `loadingNewDomainName`.
3033 boolean loadingNewDomainName;
3035 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3036 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3037 //noinspection SimplifiableIfStatement
3038 if ((hostName == null) || (currentDomainName == null)) {
3039 loadingNewDomainName = true;
3040 } else { // Determine if `hostName` equals `currentDomainName`.
3041 loadingNewDomainName = !hostName.equals(currentDomainName);
3044 // Only apply the domain settings if we are loading a new domain. This allows the user to set temporary settings for JavaScript, cookies, DOM storage, etc.
3045 if (loadingNewDomainName) {
3046 // Set the new `hostname` as the `currentDomainName`.
3047 currentDomainName = hostName;
3049 // Reset `ignorePinnedSslCertificate`.
3050 ignorePinnedSslCertificate = false;
3052 // Reset `favoriteIconBitmap` and display it in the `appbar`.
3053 favoriteIconBitmap = favoriteIconDefaultBitmap;
3054 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3056 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3057 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3058 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3060 // Get a full cursor from `domainsDatabaseHelper`.
3061 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3063 // Initialize `domainSettingsSet`.
3064 Set<String> domainSettingsSet = new HashSet<>();
3066 // Get the domain name column index.
3067 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3069 // Populate `domainSettingsSet`.
3070 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3071 // Move `domainsCursor` to the current row.
3072 domainNameCursor.moveToPosition(i);
3074 // Store the domain name in `domainSettingsSet`.
3075 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3078 // Close `domainNameCursor.
3079 domainNameCursor.close();
3081 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3082 domainSettingsApplied = false;
3083 String domainNameInDatabase = null;
3085 // Check the hostname.
3086 if (domainSettingsSet.contains(hostName)) {
3087 domainSettingsApplied = true;
3088 domainNameInDatabase = hostName;
3091 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3092 if (hostName != null) {
3093 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3094 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3095 domainSettingsApplied = true;
3096 domainNameInDatabase = "*." + hostName;
3099 // Strip out the lowest subdomain of `host`.
3100 hostName = hostName.substring(hostName.indexOf(".") + 1);
3104 // Get a handle for the shared preference. `this` references the current context.
3105 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3107 // Store the general preference information.
3108 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3109 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3110 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3111 nightMode = sharedPreferences.getBoolean("night_mode", false);
3113 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3114 // Get a cursor for the current host and move it to the first position.
3115 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3116 currentHostDomainSettingsCursor.moveToFirst();
3118 // Get the settings from the cursor.
3119 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3120 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3121 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3122 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3123 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3124 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3125 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3126 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3127 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3128 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3129 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3130 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3131 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3132 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3133 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3134 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3135 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3137 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3138 switch (nightModeInt) {
3139 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3143 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3148 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3150 javaScriptEnabled = true;
3153 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3154 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3155 pinnedDomainSslStartDate = null;
3157 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3160 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3161 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3162 pinnedDomainSslEndDate = null;
3164 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3167 // Close `currentHostDomainSettingsCursor`.
3168 currentHostDomainSettingsCursor.close();
3170 // Apply the domain settings.
3171 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3172 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3173 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3174 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3176 // Apply the font size.
3177 if (fontSize == 0) { // Apply the default font size.
3178 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3179 } else { // Apply the specified font size.
3180 mainWebView.getSettings().setTextZoom(fontSize);
3183 // Set third-party cookies status if API >= 21.
3184 if (Build.VERSION.SDK_INT >= 21) {
3185 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3188 // 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. <https://redmine.stoutner.com/issues/160>
3189 if (!urlIsLoading) {
3190 switch (userAgentString) {
3191 case "System default user agent":
3192 // Set the user agent according to the system default.
3193 switch (defaultUserAgentString) {
3194 case "WebView default user agent":
3195 // Set the user agent to `""`, which uses the default value.
3196 mainWebView.getSettings().setUserAgentString("");
3199 case "Custom user agent":
3200 // Set the custom user agent.
3201 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3205 // Use the selected user agent.
3206 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3210 case "WebView default user agent":
3211 // Set the user agent to `""`, which uses the default value.
3212 mainWebView.getSettings().setUserAgentString("");
3216 // Use the selected user agent.
3217 mainWebView.getSettings().setUserAgentString(userAgentString);
3220 // Store the applied user agent string.
3221 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3224 // 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.
3226 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3228 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3230 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3231 // Store the values from `sharedPreferences` in variables.
3232 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3233 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3234 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3235 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3236 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3238 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3240 javaScriptEnabled = true;
3243 // Apply the default settings.
3244 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3245 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3246 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3247 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3248 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3250 // Reset the pinned SSL certificate information.
3251 domainSettingsDatabaseId = -1;
3252 pinnedDomainSslCertificate = false;
3253 pinnedDomainSslIssuedToCNameString = "";
3254 pinnedDomainSslIssuedToONameString = "";
3255 pinnedDomainSslIssuedToUNameString = "";
3256 pinnedDomainSslIssuedByCNameString = "";
3257 pinnedDomainSslIssuedByONameString = "";
3258 pinnedDomainSslIssuedByUNameString = "";
3259 pinnedDomainSslStartDate = null;
3260 pinnedDomainSslEndDate = null;
3262 // Set third-party cookies status if API >= 21.
3263 if (Build.VERSION.SDK_INT >= 21) {
3264 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3267 // 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. <https://redmine.stoutner.com/issues/160>
3268 if (!urlIsLoading) {
3269 switch (defaultUserAgentString) {
3270 case "WebView default user agent":
3271 // Set the user agent to `""`, which uses the default value.
3272 mainWebView.getSettings().setUserAgentString("");
3275 case "Custom user agent":
3276 // Set the custom user agent.
3277 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3281 // Use the selected user agent.
3282 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3285 // Store the applied user agent string.
3286 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3289 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3290 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3293 // Close `domainsDatabaseHelper`.
3294 domainsDatabaseHelper.close();
3296 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3297 onTheFlyDisplayImagesSet = false;
3298 setDisplayWebpageImages();
3300 // Update the privacy icons, but only if `mainMenu` has already been populated.
3301 if (mainMenu != null) {
3302 updatePrivacyIcons(true);
3307 private void setDisplayWebpageImages() {
3308 if (!onTheFlyDisplayImagesSet) {
3309 if (domainSettingsApplied) { // Custom domain settings are applied.
3310 switch (displayWebpageImagesInt) {
3311 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3312 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3315 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3316 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3319 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3320 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3323 } else { // Default settings are applied.
3324 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3329 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3330 // Get handles for the icons.
3331 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3332 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3333 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3334 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3336 // Update `privacyIcon`.
3337 if (javaScriptEnabled) { // JavaScript is enabled.
3338 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3339 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3340 privacyIconMenuItem.setIcon(R.drawable.warning);
3341 } else { // All the dangerous features are disabled.
3342 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3345 // Update `firstPartyCookiesIcon`.
3346 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3347 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3348 } else { // First-party cookies are disabled.
3350 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3352 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3356 // Update `domStorageIcon`.
3357 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3358 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3359 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3361 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3363 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3365 } else { // JavaScript is disabled, so DOM storage is ghosted.
3367 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3369 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3373 // Update `formDataIcon`.
3374 if (saveFormDataEnabled) { // Form data is enabled.
3375 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3376 } else { // Form data is disabled.
3378 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3380 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3384 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
3385 if (runInvalidateOptionsMenu) {
3386 ActivityCompat.invalidateOptionsMenu(this);
3390 private void highlightUrlText() {
3391 String urlString = urlTextBox.getText().toString();
3393 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3394 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3395 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3396 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3399 // Get the index of the `/` immediately after the domain name.
3400 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3402 // De-emphasize the text after the domain name.
3403 if (endOfDomainName > 0) {
3404 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3408 private void loadBookmarksFolder() {
3409 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3410 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3412 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3413 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3415 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3416 // Inflate the individual item layout. `false` does not attach it to the root.
3417 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3421 public void bindView(View view, Context context, Cursor cursor) {
3422 // Get handles for the views.
3423 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3424 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3426 // Get the favorite icon byte array from the `Cursor`.
3427 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3429 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3430 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3432 // Display the bitmap in `bookmarkFavoriteIcon`.
3433 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3435 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3436 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3437 bookmarkNameTextView.setText(bookmarkNameString);
3439 // Make the font bold for folders.
3440 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3441 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3442 } else { // Reset the font to default for normal bookmarks.
3443 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3448 // Populate the `ListView` with the adapter.
3449 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3451 // Set the bookmarks drawer title.
3452 if (currentBookmarksFolder.isEmpty()) {
3453 bookmarksTitleTextView.setText(R.string.bookmarks);
3455 bookmarksTitleTextView.setText(currentBookmarksFolder);