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.Activity;
26 import android.app.DialogFragment;
27 import android.app.DownloadManager;
28 import android.content.BroadcastReceiver;
29 import android.content.ClipData;
30 import android.content.ClipboardManager;
31 import android.content.Context;
32 import android.content.Intent;
33 import android.content.IntentFilter;
34 import android.content.SharedPreferences;
35 import android.content.res.Configuration;
36 import android.database.Cursor;
37 import android.graphics.Bitmap;
38 import android.graphics.BitmapFactory;
39 import android.graphics.Typeface;
40 import android.graphics.drawable.BitmapDrawable;
41 import android.graphics.drawable.Drawable;
42 import android.net.Uri;
43 import android.net.http.SslCertificate;
44 import android.net.http.SslError;
45 import android.os.Build;
46 import android.os.Bundle;
47 import android.os.Handler;
48 import android.preference.PreferenceManager;
49 import android.print.PrintDocumentAdapter;
50 import android.print.PrintManager;
51 import android.support.annotation.NonNull;
52 import android.support.design.widget.CoordinatorLayout;
53 import android.support.design.widget.FloatingActionButton;
54 import android.support.design.widget.NavigationView;
55 import android.support.design.widget.Snackbar;
56 import android.support.v4.app.ActivityCompat;
57 import android.support.v4.content.ContextCompat;
58 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
59 import android.support.v4.content.pm.ShortcutInfoCompat;
60 import android.support.v4.content.pm.ShortcutManagerCompat;
61 import android.support.v4.graphics.drawable.IconCompat;
62 import android.support.v4.view.GravityCompat;
63 import android.support.v4.widget.DrawerLayout;
64 import android.support.v4.widget.SwipeRefreshLayout;
65 import android.support.v7.app.ActionBar;
66 import android.support.v7.app.ActionBarDrawerToggle;
67 import android.support.v7.app.AppCompatActivity;
68 import android.support.v7.app.AppCompatDialogFragment;
69 import android.support.v7.widget.Toolbar;
70 import android.text.Editable;
71 import android.text.Spanned;
72 import android.text.TextWatcher;
73 import android.text.style.ForegroundColorSpan;
74 import android.util.Log;
75 import android.util.Patterns;
76 import android.view.ContextMenu;
77 import android.view.GestureDetector;
78 import android.view.KeyEvent;
79 import android.view.Menu;
80 import android.view.MenuItem;
81 import android.view.MotionEvent;
82 import android.view.View;
83 import android.view.ViewGroup;
84 import android.view.WindowManager;
85 import android.view.inputmethod.InputMethodManager;
86 import android.webkit.CookieManager;
87 import android.webkit.HttpAuthHandler;
88 import android.webkit.SslErrorHandler;
89 import android.webkit.WebBackForwardList;
90 import android.webkit.WebChromeClient;
91 import android.webkit.WebResourceResponse;
92 import android.webkit.WebStorage;
93 import android.webkit.WebView;
94 import android.webkit.WebViewClient;
95 import android.webkit.WebViewDatabase;
96 import android.widget.CursorAdapter;
97 import android.widget.EditText;
98 import android.widget.FrameLayout;
99 import android.widget.ImageView;
100 import android.widget.LinearLayout;
101 import android.widget.ListView;
102 import android.widget.ProgressBar;
103 import android.widget.RadioButton;
104 import android.widget.RelativeLayout;
105 import android.widget.TextView;
107 import com.stoutner.privacybrowser.BannerAd;
108 import com.stoutner.privacybrowser.BuildConfig;
109 import com.stoutner.privacybrowser.R;
110 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
111 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
112 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
113 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
114 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
115 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
116 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
117 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
118 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
119 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
120 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
121 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
122 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
123 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
124 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
125 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
127 import java.io.BufferedReader;
128 import java.io.ByteArrayInputStream;
129 import java.io.ByteArrayOutputStream;
131 import java.io.IOException;
132 import java.io.InputStreamReader;
133 import java.io.UnsupportedEncodingException;
134 import java.net.MalformedURLException;
136 import java.net.URLDecoder;
137 import java.net.URLEncoder;
138 import java.util.Date;
139 import java.util.HashMap;
140 import java.util.HashSet;
141 import java.util.LinkedList;
142 import java.util.List;
143 import java.util.Map;
144 import java.util.Set;
145 import java.util.regex.Pattern;
147 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
148 public class MainWebViewActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener, CreateBookmarkDialog.CreateBookmarkListener,
149 CreateBookmarkFolderDialog.CreateBookmarkFolderListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener, DownloadFileDialog.DownloadFileListener,
150 DownloadImageDialog.DownloadImageListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener,
151 NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener,
152 UrlHistoryDialog.UrlHistoryListener {
154 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`,
155 // `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
156 // `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`,
157 // and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
158 public static boolean darkTheme;
160 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
161 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
162 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
163 public static Bitmap favoriteIconBitmap;
165 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
166 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
167 public static String formattedUrlString;
169 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
170 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
171 public static SslCertificate sslCertificate;
173 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
174 public static String orbotStatus;
176 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
177 public static String webViewTitle;
179 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
180 public static String appliedUserAgentString;
182 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
183 public static boolean displayWebpageImagesBoolean;
185 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
186 public static boolean reloadOnRestart;
188 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
189 public static boolean loadUrlOnRestart;
191 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
192 public static boolean restartFromBookmarksActivity;
194 // `easyListVersion` is public static so it can be accessed from `AboutTabFragment`. It is also used in `onCreate()`.
195 public static String easyListVersion;
197 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
198 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
199 public static String currentBookmarksFolder;
201 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
202 public static int domainSettingsDatabaseId;
204 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
205 public static String pinnedDomainSslIssuedToCNameString;
206 public static String pinnedDomainSslIssuedToONameString;
207 public static String pinnedDomainSslIssuedToUNameString;
208 public static String pinnedDomainSslIssuedByCNameString;
209 public static String pinnedDomainSslIssuedByONameString;
210 public static String pinnedDomainSslIssuedByUNameString;
211 public static Date pinnedDomainSslStartDate;
212 public static Date pinnedDomainSslEndDate;
215 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
216 private ActionBar appBar;
218 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
219 private boolean navigatingHistory;
221 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
222 private Bitmap favoriteIconDefaultBitmap;
224 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
225 private DrawerLayout drawerLayout;
227 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
228 private CoordinatorLayout rootCoordinatorLayout;
230 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
231 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
232 private WebView mainWebView;
234 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
235 private FrameLayout fullScreenVideoFrameLayout;
237 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
238 private SwipeRefreshLayout swipeRefreshLayout;
240 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
241 private RelativeLayout urlAppBarRelativeLayout;
243 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
244 private ImageView favoriteIconImageView;
246 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
247 private CookieManager cookieManager;
249 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
250 private final Map<String, String> customHeaders = new HashMap<>();
252 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
253 private boolean javaScriptEnabled;
255 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
256 private boolean firstPartyCookiesEnabled;
258 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
259 private boolean thirdPartyCookiesEnabled;
261 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
262 private boolean domStorageEnabled;
264 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
265 private boolean saveFormDataEnabled;
267 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
268 private boolean nightMode;
270 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
271 private boolean swipeToRefreshEnabled;
273 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
274 private String homepage;
276 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
277 private String searchURL;
279 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
280 private boolean adBlockerEnabled;
282 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
283 private Runtime privacyBrowserRuntime;
285 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
286 private boolean incognitoModeEnabled;
288 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
289 private boolean fullScreenBrowsingModeEnabled;
291 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
292 private boolean inFullScreenBrowsingMode;
294 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
295 private boolean hideSystemBarsOnFullscreen;
297 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
298 private boolean translucentNavigationBarOnFullscreen;
300 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
301 private boolean reapplyDomainSettingsOnRestart;
303 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
304 private String currentDomainName;
306 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
307 private boolean ignorePinnedSslCertificate;
309 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
310 private boolean waitingForOrbot;
312 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
313 private boolean domainSettingsApplied;
315 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
316 private int displayWebpageImagesInt;
318 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
319 private boolean onTheFlyDisplayImagesSet;
321 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
322 private String waitingForOrbotHTMLString;
324 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
325 private String privateDataDirectoryString;
327 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
328 private LinearLayout findOnPageLinearLayout;
330 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
331 private EditText findOnPageEditText;
333 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
334 private Menu mainMenu;
336 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
337 private ActionBarDrawerToggle drawerToggle;
339 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
340 private Toolbar supportAppBar;
342 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
343 private EditText urlTextBox;
345 // The color spans are used in `onCreate()` and `highlightUrlText()`.
346 private ForegroundColorSpan redColorSpan;
347 private ForegroundColorSpan initialGrayColorSpan;
348 private ForegroundColorSpan finalGrayColorSpan;
350 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
353 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
354 private SslErrorHandler sslErrorHandler;
356 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
357 private static HttpAuthHandler httpAuthHandler;
359 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
360 private InputMethodManager inputMethodManager;
362 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
363 private RelativeLayout mainWebViewRelativeLayout;
365 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
366 private boolean urlIsLoading;
368 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
369 private boolean pinnedDomainSslCertificate;
371 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
372 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
374 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
375 private ListView bookmarksListView;
377 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
378 private TextView bookmarksTitleTextView;
380 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
381 private Cursor bookmarksCursor;
383 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
384 private CursorAdapter bookmarksCursorAdapter;
386 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
387 private String oldFolderNameString;
390 // 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.
391 @SuppressLint({"SetJavaScriptEnabled"})
392 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
393 @SuppressWarnings("deprecation")
394 protected void onCreate(Bundle savedInstanceState) {
395 // Get a handle for `sharedPreferences`. `this` references the current context.
396 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
398 // Get the theme preference.
399 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
401 // Set the activity theme.
403 setTheme(R.style.PrivacyBrowserDark);
405 setTheme(R.style.PrivacyBrowserLight);
408 // Run the default commands.
409 super.onCreate(savedInstanceState);
411 Log.i("BlockLists", "Begin populating block lists.");
413 // Initialize the block lists.
414 List<String> mainWhiteList = new LinkedList<>();
415 List<String[]> multiEntryWhiteList = new LinkedList<>();
416 List<String> mainBlockList = new LinkedList<>();
417 List<String> initialBlockList = new LinkedList<>();
418 List<String> finalBlockList = new LinkedList<>();
419 List<String[]> multiEntryBlockList = new LinkedList<>();
420 List<String[]> multiEntryInitialBlockList = new LinkedList<>();
421 List<String[]> multiEntryFinalBlockList = new LinkedList<>();
422 List<String[]> domainBlockList = new LinkedList<>();
423 List<String[]> domainInitialBlockList = new LinkedList<>();
424 List<String[]> domainFinalBlockList = new LinkedList<>();
425 List<String[]> domainMultiEntryBlockList = new LinkedList<>();
426 List<String[]> domainRegularExpressionBlockList = new LinkedList<>();
427 List<String> regularExpressionBlockList = new LinkedList<>();
429 // Populate the block lists.
431 // Load `easylist.txt` into a `BufferedReader`.
432 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("easylist.txt")));
434 // Create a string for storing the block list entries.
435 String blockListEntry;
438 while ((blockListEntry = bufferedReader.readLine()) != null) {
439 //noinspection StatementWithEmptyBody
440 if (blockListEntry.contains("##") || blockListEntry.contains("#?#") || blockListEntry.contains("#@#") || blockListEntry.startsWith("[")) {
441 // Entries that contain `##`, `#?#`, and `#@#` are for hiding elements in the main page's HTML. Entries that start with `[` describe the AdBlock compatibility level.
443 // Do nothing. Privacy Browser does not currently use these entries.
445 //Log.i("BlackLists", "Not added: " + adBlockerEntry);
446 } else if (blockListEntry.startsWith("!")){ // Entries that begin with `!` are comments.
447 if (blockListEntry.startsWith("! Version:")) {
448 // Store the EasyList version number.
449 easyListVersion = blockListEntry.substring(11);
452 //Log.i("BlackLists", "Not added: " + adBlockerEntry);
453 } else if (blockListEntry.startsWith("@@")) { // Entries that begin with `@@` are excludes (whitelists).
454 // mainWhiteList.add(blockListEntry.substring(2));
456 //Log.i("BlockLists", "Main white list added: " + blockListEntry.substring(2, blockListEntry.length()));
457 } else if (blockListEntry.endsWith("|")){ // Entries that end with `|` match against the end of the URL.
458 // Strip out the final "|"
459 blockListEntry = blockListEntry.substring(0, blockListEntry.length() - 1);
461 // Strip out any initial `||`. They are redundant in this case because the block list entry is being matched against the end of the URL.
462 if (blockListEntry.startsWith("||")) {
463 blockListEntry = blockListEntry.substring(2);
466 if (blockListEntry.contains("*")) {
467 int wildcardIndex = blockListEntry.indexOf("*");
469 String firstEntry = blockListEntry.substring(0, wildcardIndex);
470 String secondEntry = blockListEntry.substring(wildcardIndex + 1);
472 if (firstEntry.endsWith("^")) {
473 String firstEntryBase = firstEntry.substring(0, firstEntry.length() - 1);
475 String firstEntry1 = firstEntryBase + ":";
476 String firstEntry2 = firstEntryBase + "/";
477 String firstEntry3 = firstEntryBase + "?";
478 String firstEntry4 = firstEntryBase + "=";
479 String firstEntry5 = firstEntryBase + "&";
481 String[] doubleEntry1 = {firstEntry1, secondEntry};
482 String[] doubleEntry2 = {firstEntry2, secondEntry};
483 String[] doubleEntry3 = {firstEntry3, secondEntry};
484 String[] doubleEntry4 = {firstEntry4, secondEntry};
485 String[] doubleEntry5 = {firstEntry5, secondEntry};
487 multiEntryFinalBlockList.add(doubleEntry1);
488 multiEntryFinalBlockList.add(doubleEntry2);
489 multiEntryFinalBlockList.add(doubleEntry3);
490 multiEntryFinalBlockList.add(doubleEntry4);
491 multiEntryFinalBlockList.add(doubleEntry5);
493 //Log.i("BlockLists", "Multi entry final block list added: " + firstEntry1 + " , " + secondEntry);
494 //Log.i("BlockLists", "Multi entry final block list added: " + firstEntry2 + " , " + secondEntry);
495 //Log.i("BlockLists", "Multi entry final block list added: " + firstEntry3 + " , " + secondEntry);
496 //Log.i("BlockLists", "Multi entry final block list added: " + firstEntry4 + " , " + secondEntry);
497 //Log.i("BlockLists", "Multi entry final block list added: " + firstEntry5 + " , " + secondEntry);
499 String[] doubleEntry = {firstEntry, secondEntry};
501 multiEntryFinalBlockList.add(doubleEntry);
503 //Log.i("BlockLists", "Multi entry final block list added: " + firstEntry + " , " + secondEntry);
506 finalBlockList.add(blockListEntry);
508 //Log.i("BlockLists", "Final block list added: " + blockListEntry);
510 } else if (blockListEntry.contains("$")) { // Entries that contain `$` use filter options.
511 // Strip out any initial `||`. These will be treated like any other entry.
512 if (blockListEntry.startsWith("||")) {
513 blockListEntry = blockListEntry.substring(2);
516 if (blockListEntry.contains("third-party")) {
517 // Log.i("BlockLists", "Not added: " + blockListEntry);
518 } else if (blockListEntry.substring(blockListEntry.indexOf("$")).contains("domain")) {
519 if (blockListEntry.contains("~")) { // Whitelist.
522 // Separate the filters.
523 String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
524 String filters = blockListEntry.substring(blockListEntry.indexOf("$") + 1);
525 String domains = filters.substring(filters.indexOf("domain=") + 7);
527 // Only process the block list item if the entry is not null. Some lines in EasyList begin with `$websocket`, which create a null entry.
528 if (!entry.equals("")) {
532 if (domains.contains("|")) {
533 // Get the first domain.
534 domain = domains.substring(0, domains.indexOf("|"));
536 // Remove the first domain from the list.
537 domains = domains.substring(domains.indexOf("|") + 1);
542 if (entry.contains("*")) {
543 int wildcardIndex = entry.indexOf("*");
545 String firstEntry = entry.substring(0, wildcardIndex);
546 String secondEntry = entry.substring(wildcardIndex + 1);
548 if (firstEntry.endsWith("^")) {
549 String firstEntryBase = firstEntry.substring(0, firstEntry.length() - 1);
551 String firstEntry1 = firstEntryBase + ":";
552 String firstEntry2 = firstEntryBase + "/";
553 String firstEntry3 = firstEntryBase + "?";
554 String firstEntry4 = firstEntryBase + "=";
555 String firstEntry5 = firstEntryBase + "&";
557 String[] domainDoubleEntry1 = {domain, firstEntry1, secondEntry};
558 String[] domainDoubleEntry2 = {domain, firstEntry2, secondEntry};
559 String[] domainDoubleEntry3 = {domain, firstEntry3, secondEntry};
560 String[] domainDoubleEntry4 = {domain, firstEntry4, secondEntry};
561 String[] domainDoubleEntry5 = {domain, firstEntry5, secondEntry};
563 domainMultiEntryBlockList.add(domainDoubleEntry1);
564 domainMultiEntryBlockList.add(domainDoubleEntry2);
565 domainMultiEntryBlockList.add(domainDoubleEntry3);
566 domainMultiEntryBlockList.add(domainDoubleEntry4);
567 domainMultiEntryBlockList.add(domainDoubleEntry5);
569 //Log.i("BlockLists", "Domain ^ double entry block list added: " + domain + " , " + firstEntry1 + " , " + secondEntry);
570 //Log.i("BlockLists", "Domain ^ double entry block list added: " + domain + " , " + firstEntry2 + " , " + secondEntry);
571 //Log.i("BlockLists", "Domain ^ double entry block list added: " + domain + " , " + firstEntry3 + " , " + secondEntry);
572 //Log.i("BlockLists", "Domain ^ double entry block list added: " + domain + " , " + firstEntry4 + " , " + secondEntry);
573 //Log.i("BlockLists", "Domain ^ double entry block list added: " + domain + " , " + firstEntry5 + " , " + secondEntry);
575 String[] domainDoubleEntry = {domain, firstEntry, secondEntry};
577 domainMultiEntryBlockList.add(domainDoubleEntry);
579 //Log.i("BlockLists", "Domain double entry block list added: " + domain + " , " + firstEntry + " , " + secondEntry);
581 } else if (entry.endsWith("^")) {
582 String entryBase = entry.substring(0, entry.length() - 1);
584 String entry1 = entryBase + ":";
585 String entry2 = entryBase + "/";
586 String entry3 = entryBase + "?";
587 String entry4 = entryBase + "=";
588 String entry5 = entryBase + "&";
590 String[] domainEntry1 = {domain, entry1};
591 String[] domainEntry2 = {domain, entry2};
592 String[] domainEntry3 = {domain, entry3};
593 String[] domainEntry4 = {domain, entry4};
594 String[] domainEntry5 = {domain, entry5};
596 domainBlockList.add(domainEntry1);
597 domainBlockList.add(domainEntry2);
598 domainBlockList.add(domainEntry3);
599 domainBlockList.add(domainEntry4);
600 domainBlockList.add(domainEntry5);
602 //Log.i("BlockLists", "Domain ^ block list added: " + domain + " , " + entry1);
603 //Log.i("BlockLists", "Domain ^ block list added: " + domain + " , " + entry2);
604 //Log.i("BlockLists", "Domain ^ block list added: " + domain + " , " + entry3);
605 //Log.i("BlockLists", "Domain ^ block list added: " + domain + " , " + entry4);
606 //Log.i("BlockLists", "Domain ^ block list added: " + domain + " , " + entry5);
607 } else if (entry.startsWith("^")) {
608 String entryBase = entry.substring(1);
610 String entry1 = ":" + entryBase;
611 String entry2 = ":" + entryBase;
612 String entry3 = ":" + entryBase;
613 String entry4 = ":" + entryBase;
614 String entry5 = ":" + entryBase;
616 String[] domainEntry1 = {domain, entry1};
617 String[] domainEntry2 = {domain, entry2};
618 String[] domainEntry3 = {domain, entry3};
619 String[] domainEntry4 = {domain, entry4};
620 String[] domainEntry5 = {domain, entry5};
622 domainBlockList.add(domainEntry1);
623 domainBlockList.add(domainEntry2);
624 domainBlockList.add(domainEntry3);
625 domainBlockList.add(domainEntry4);
626 domainBlockList.add(domainEntry5);
628 //Log.i("BlockLists", "Domain ^ block list added: " + domain + " , " + entry1);
629 //Log.i("BlockLists", "Domain ^ block list added: " + domain + " , " + entry2);
630 //Log.i("BlockLists", "Domain ^ block list added: " + domain + " , " + entry3);
631 //Log.i("BlockLists", "Domain ^ block list added: " + domain + " , " + entry4);
632 //Log.i("BlockLists", "Domain ^ block list added: " + domain + " , " + entry5);
633 } else if (entry.startsWith("|")) {
634 // Remove the initial `|`;
635 String entryBase = entry.substring(1);
637 //noinspection StatementWithEmptyBody
638 if (entryBase.equals("http://") || entryBase.equals("https://")) {
639 // Do nothing. These entries will entirely block the website.
640 // Often the original entry blocks `$script` but Privacy Browser does not currently differentiate between scripts and other entries.
642 String[] domainEntry = {domain, entryBase};
644 domainInitialBlockList.add(domainEntry);
646 //Log.i("BlockLists", "Domain initial block list added: " + domain + " , " + entryBase);
648 } else if (entry.endsWith("|")) {
649 // Remove the final `|`.
650 String entryBase = entry.substring(0, entry.length() - 1);
652 String[] domainEntry = {domain, entryBase};
654 domainFinalBlockList.add(domainEntry);
656 Log.i("BlockLists", "Domain final block list added: " + domain + " , " + entryBase);
657 } else if (entry.contains("\\")) {
658 String[] domainEntry = {domain, entry};
660 domainRegularExpressionBlockList.add(domainEntry);
662 // Log.i("BlockLists", "Domain regular expression block list added: " + domain + " , " + entry);
664 String[] domainEntry = {domain, entry};
666 domainBlockList.add(domainEntry);
668 //Log.i("BlockLists", "Domain block list added: " + domain + " , " + entry);
670 } while (domains.contains("|"));
673 } else if (blockListEntry.contains("~")) { // Whitelist entries.
674 // Remove the filter options.
675 blockListEntry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
677 // Strip any trailing `*`.
678 if (blockListEntry.endsWith("*")) {
679 blockListEntry = blockListEntry.substring(0, blockListEntry.length() -1);
682 if (blockListEntry.contains("*")) {
683 int wildcardIndex = blockListEntry.indexOf("*");
685 String firstEntry = blockListEntry.substring(0, wildcardIndex);
686 String secondEntry = blockListEntry.substring(wildcardIndex + 1);
688 if (firstEntry.endsWith("^")) {
689 String firstEntryBase = firstEntry.substring(0, firstEntry.length() - 1);
691 String firstEntry1 = firstEntryBase + ":";
692 String firstEntry2 = firstEntryBase + "/";
693 String firstEntry3 = firstEntryBase + "?";
694 String firstEntry4 = firstEntryBase + "=";
695 String firstEntry5 = firstEntryBase + "&";
697 String[] doubleEntry1 = {firstEntry1, secondEntry};
698 String[] doubleEntry2 = {firstEntry2, secondEntry};
699 String[] doubleEntry3 = {firstEntry3, secondEntry};
700 String[] doubleEntry4 = {firstEntry4, secondEntry};
701 String[] doubleEntry5 = {firstEntry5, secondEntry};
703 multiEntryWhiteList.add(doubleEntry1);
704 multiEntryWhiteList.add(doubleEntry2);
705 multiEntryWhiteList.add(doubleEntry3);
706 multiEntryWhiteList.add(doubleEntry4);
707 multiEntryWhiteList.add(doubleEntry5);
709 //Log.i("BlockLists", "Multi entry white list added: " + firstEntry1 + " , " + secondEntry);
710 //Log.i("BlockLists", "Multi entry white list added: " + firstEntry2 + " , " + secondEntry);
711 //Log.i("BlockLists", "Multi entry white list added: " + firstEntry3 + " , " + secondEntry);
712 //Log.i("BlockLists", "Multi entry white list added: " + firstEntry4 + " , " + secondEntry);
713 //Log.i("BlockLists", "Multi entry white list added: " + firstEntry5 + " , " + secondEntry);
715 String[] doubleEntry = {firstEntry, secondEntry};
717 multiEntryWhiteList.add(doubleEntry);
719 //Log.i("BlockLists", "Multi entry white list added: " + firstEntry + " , " + secondEntry);
722 if (blockListEntry.endsWith("^")) {
723 String blockListEntryBase = blockListEntry.substring(0, blockListEntry.length() - 1);
725 String blockListEntry1 = blockListEntryBase + ":";
726 String blockListEntry2 = blockListEntryBase + "/";
727 String blockListEntry3 = blockListEntryBase + "?";
728 String blockListEntry4 = blockListEntryBase + "=";
729 String blockListEntry5 = blockListEntryBase + "&";
731 mainWhiteList.add(blockListEntry1);
732 mainWhiteList.add(blockListEntry2);
733 mainWhiteList.add(blockListEntry3);
734 mainWhiteList.add(blockListEntry4);
735 mainWhiteList.add(blockListEntry5);
737 // Log.i("BlockLists", "Main white list added: " + blockListEntry1);
738 // Log.i("BlockLists", "Main white list added: " + blockListEntry2);
739 // Log.i("BlockLists", "Main white list added: " + blockListEntry3);
740 // Log.i("BlockLists", "Main white list added: " + blockListEntry4);
741 // Log.i("BlockLists", "Main white list added: " + blockListEntry5);
743 mainWhiteList.add(blockListEntry);
745 // Log.i("BlockLists", "Main white list added: " + blockListEntry);
748 } else if (blockListEntry.contains("\\")) { // Regular expressions.
749 // Remove the filter options.
750 blockListEntry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
752 regularExpressionBlockList.add(blockListEntry);
754 //Log.i("BlockLists", "Regular expression list added: " + blockListEntry);
756 // Remove the filter options.
757 blockListEntry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
759 // Strip any trailing `*` or `^`. Many of these entries have `^$`, which seem redundant for the purposes of Privacy Browser.
760 if (blockListEntry.endsWith("*") || blockListEntry.endsWith("^")) {
761 blockListEntry = blockListEntry.substring(0, blockListEntry.length() - 1);
764 if (blockListEntry.contains("*")) { // Use a multi entry list.
765 int wildcardIndex = blockListEntry.indexOf("*");
767 String firstEntry = blockListEntry.substring(0, wildcardIndex);
768 String secondEntry = blockListEntry.substring(wildcardIndex + 1);
770 // Remove `.*` if it appears at the beginning of the second entry.
771 if (secondEntry.startsWith(".*")) {
772 secondEntry = secondEntry.substring(2);
775 // Create a third entry if required.
776 if (secondEntry.contains("*")) {
777 wildcardIndex = secondEntry.indexOf("*");
779 String thirdEntry = secondEntry.substring(wildcardIndex + 1);
780 secondEntry = secondEntry.substring(0, wildcardIndex);
782 if (firstEntry.endsWith("^")) {
783 String firstEntryBase = firstEntry.substring(0, firstEntry.length() - 1);
785 String firstEntry1 = firstEntryBase + ":";
786 String firstEntry2 = firstEntryBase + "/";
787 String firstEntry3 = firstEntryBase + "?";
788 String firstEntry4 = firstEntryBase + "=";
789 String firstEntry5 = firstEntryBase + "&";
791 if (thirdEntry.endsWith("|")) {
792 thirdEntry = thirdEntry.substring(0, thirdEntry.length() - 1);
794 String[] tripleEntry1 = {firstEntry1, secondEntry, thirdEntry};
795 String[] tripleEntry2 = {firstEntry2, secondEntry, thirdEntry};
796 String[] tripleEntry3 = {firstEntry3, secondEntry, thirdEntry};
797 String[] tripleEntry4 = {firstEntry4, secondEntry, thirdEntry};
798 String[] tripleEntry5 = {firstEntry5, secondEntry, thirdEntry};
800 multiEntryFinalBlockList.add(tripleEntry1);
801 multiEntryFinalBlockList.add(tripleEntry2);
802 multiEntryFinalBlockList.add(tripleEntry3);
803 multiEntryFinalBlockList.add(tripleEntry4);
804 multiEntryFinalBlockList.add(tripleEntry5);
806 //Log.i("BlockLists", "Multi entry final tripple block list added: " + firstEntry1 + " , " + secondEntry + " , " + thirdEntry);
807 //Log.i("BlockLists", "Multi entry final tripple block list added: " + firstEntry2 + " , " + secondEntry + " , " + thirdEntry);
808 //Log.i("BlockLists", "Multi entry final tripple block list added: " + firstEntry3 + " , " + secondEntry + " , " + thirdEntry);
809 //Log.i("BlockLists", "Multi entry final tripple block list added: " + firstEntry4 + " , " + secondEntry + " , " + thirdEntry);
810 //Log.i("BlockLists", "Multi entry final tripple block list added: " + firstEntry5 + " , " + secondEntry + " , " + thirdEntry);
812 String[] tripleEntry1 = {firstEntry1, secondEntry, thirdEntry};
813 String[] tripleEntry2 = {firstEntry2, secondEntry, thirdEntry};
814 String[] tripleEntry3 = {firstEntry3, secondEntry, thirdEntry};
815 String[] tripleEntry4 = {firstEntry4, secondEntry, thirdEntry};
816 String[] tripleEntry5 = {firstEntry5, secondEntry, thirdEntry};
818 multiEntryBlockList.add(tripleEntry1);
819 multiEntryBlockList.add(tripleEntry2);
820 multiEntryBlockList.add(tripleEntry3);
821 multiEntryBlockList.add(tripleEntry4);
822 multiEntryBlockList.add(tripleEntry5);
824 //Log.i("BlockLists", "Multi entry tripple block list added: " + firstEntry1 + " , " + secondEntry + " , " + thirdEntry);
825 //Log.i("BlockLists", "Multi entry tripple block list added: " + firstEntry2 + " , " + secondEntry + " , " + thirdEntry);
826 //Log.i("BlockLists", "Multi entry tripple block list added: " + firstEntry3 + " , " + secondEntry + " , " + thirdEntry);
827 //Log.i("BlockLists", "Multi entry tripple block list added: " + firstEntry4 + " , " + secondEntry + " , " + thirdEntry);
828 //Log.i("BlockLists", "Multi entry tripple block list added: " + firstEntry5 + " , " + secondEntry + " , " + thirdEntry);
831 String[] tripleEntry = {firstEntry, secondEntry, thirdEntry};
833 multiEntryBlockList.add(tripleEntry);
835 // Log.i("BlockLists", "Multi entry tripple block list added: " + firstEntry + " , " + secondEntry + " , " + thirdEntry);
837 } else { // This is a double entry.
838 if (firstEntry.startsWith("|")) {
839 String[] doubleEntry = {firstEntry.substring(1), secondEntry};
841 multiEntryInitialBlockList.add(doubleEntry);
843 //Log.i("BlockLists", "Multi entry initial block list added: " + firstEntry.substring(1) + " , " + secondEntry);
844 } else if (firstEntry.startsWith("^")) {
845 String firstEntryBase = firstEntry.substring(1);
847 String firstEntry1 = ":" + firstEntryBase;
848 String firstEntry2 = "/" + firstEntryBase;
849 String firstEntry3 = "?" + firstEntryBase;
850 String firstEntry4 = "=" + firstEntryBase;
851 String firstEntry5 = "&" + firstEntryBase;
853 String[] doubleEntry1 = {firstEntry1, secondEntry};
854 String[] doubleEntry2 = {firstEntry2, secondEntry};
855 String[] doubleEntry3 = {firstEntry3, secondEntry};
856 String[] doubleEntry4 = {firstEntry4, secondEntry};
857 String[] doubleEntry5 = {firstEntry5, secondEntry};
859 multiEntryBlockList.add(doubleEntry1);
860 multiEntryBlockList.add(doubleEntry2);
861 multiEntryBlockList.add(doubleEntry3);
862 multiEntryBlockList.add(doubleEntry4);
863 multiEntryBlockList.add(doubleEntry5);
865 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry1 + " , " + secondEntry);
866 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry2 + " , " + secondEntry);
867 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry3 + " , " + secondEntry);
868 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry4 + " , " + secondEntry);
869 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry5 + " , " + secondEntry);
870 } else if (firstEntry.endsWith("^")) {
871 String firstEntryBase = firstEntry.substring(0, firstEntry.length() - 1);
873 String firstEntry1 = firstEntryBase + ":";
874 String firstEntry2 = firstEntryBase + "/";
875 String firstEntry3 = firstEntryBase + "?";
876 String firstEntry4 = firstEntryBase + "=";
877 String firstEntry5 = firstEntryBase + "&";
879 String[] doubleEntry1 = {firstEntry1, secondEntry};
880 String[] doubleEntry2 = {firstEntry2, secondEntry};
881 String[] doubleEntry3 = {firstEntry3, secondEntry};
882 String[] doubleEntry4 = {firstEntry4, secondEntry};
883 String[] doubleEntry5 = {firstEntry5, secondEntry};
885 multiEntryBlockList.add(doubleEntry1);
886 multiEntryBlockList.add(doubleEntry2);
887 multiEntryBlockList.add(doubleEntry3);
888 multiEntryBlockList.add(doubleEntry4);
889 multiEntryBlockList.add(doubleEntry5);
891 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry1 + " , " + secondEntry);
892 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry2 + " , " + secondEntry);
893 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry3 + " , " + secondEntry);
894 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry4 + " , " + secondEntry);
895 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry5 + " , " + secondEntry);
896 } else if (secondEntry.startsWith("^")) {
897 String secondEntryBase = secondEntry.substring(1);
899 String secondEntry1 = ":" + secondEntryBase;
900 String secondEntry2 = "/" + secondEntryBase;
901 String secondEntry3 = "?" + secondEntryBase;
902 String secondEntry4 = "=" + secondEntryBase;
903 String secondEntry5 = "&" + secondEntryBase;
905 String[] doubleEntry1 = {firstEntry, secondEntry1};
906 String[] doubleEntry2 = {firstEntry, secondEntry2};
907 String[] doubleEntry3 = {firstEntry, secondEntry3};
908 String[] doubleEntry4 = {firstEntry, secondEntry4};
909 String[] doubleEntry5 = {firstEntry, secondEntry5};
911 multiEntryBlockList.add(doubleEntry1);
912 multiEntryBlockList.add(doubleEntry2);
913 multiEntryBlockList.add(doubleEntry3);
914 multiEntryBlockList.add(doubleEntry4);
915 multiEntryBlockList.add(doubleEntry5);
917 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry1);
918 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry2);
919 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry3);
920 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry4);
921 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry5);
922 } else if (secondEntry.endsWith("^")) {
923 String secondEntryBase = secondEntry.substring(0, secondEntry.length() - 1);
925 String secondEntry1 = secondEntryBase + ":";
926 String secondEntry2 = secondEntryBase + "/";
927 String secondEntry3 = secondEntryBase + "?";
928 String secondEntry4 = secondEntryBase + "=";
929 String secondEntry5 = secondEntryBase + "&";
931 String[] doubleEntry1 = {firstEntry, secondEntry1};
932 String[] doubleEntry2 = {firstEntry, secondEntry2};
933 String[] doubleEntry3 = {firstEntry, secondEntry3};
934 String[] doubleEntry4 = {firstEntry, secondEntry4};
935 String[] doubleEntry5 = {firstEntry, secondEntry5};
937 String[] doubleEntryFinal = {firstEntry, secondEntryBase};
939 multiEntryBlockList.add(doubleEntry1);
940 multiEntryBlockList.add(doubleEntry2);
941 multiEntryBlockList.add(doubleEntry3);
942 multiEntryBlockList.add(doubleEntry4);
943 multiEntryBlockList.add(doubleEntry5);
945 multiEntryFinalBlockList.add(doubleEntryFinal);
947 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry1);
948 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry2);
949 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry3);
950 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry4);
951 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry5);
953 //Log.i("BlockLists", "Multi entry final block list added: " + firstEntry + " , " + secondEntryBase);
955 String[] doubleEntry = {firstEntry, secondEntry};
957 multiEntryBlockList.add(doubleEntry);
959 //Log.i("BlockLists", "Multi entry block list added: " + firstEntry + " , " + secondEntry);
962 } else if (blockListEntry.startsWith("|")) { // Populate the initial block list.
963 // Strip the initial `|`.
964 blockListEntry = blockListEntry.substring(1);
966 // Populate the initial block list.
967 initialBlockList.add(blockListEntry);
969 //Log.i("BlockLists", "Initial block list added: " + blockListEntry);
970 } else { // Populate the main block list.
971 mainBlockList.add(blockListEntry);
973 //Log.i("BlockLists", "Main block list added: " + blockListEntry);
976 } else { // Populate the standard lists.
977 // Strip out any initial `||`. These will be treated like any other entry.
978 if (blockListEntry.startsWith("||")) {
979 blockListEntry = blockListEntry.substring(2);
982 // Strip out any initial `*`.
983 if (blockListEntry.startsWith("*")) {
984 blockListEntry = blockListEntry.substring(1);
987 // Strip out any trailing `*`.
988 if (blockListEntry.endsWith("*")) {
989 blockListEntry = blockListEntry.substring(0, blockListEntry.length() - 1);
992 if (blockListEntry.contains("*")) { // Entries that contain a `*` in the middle have to be treated specially.
993 int wildcardIndex = blockListEntry.indexOf("*");
995 String firstEntry = blockListEntry.substring(0, wildcardIndex);
996 String secondEntry = blockListEntry.substring(wildcardIndex + 1);
998 // Remove `.*` if it appears at the beginning of the second entry.
999 if (secondEntry.startsWith(".*")) {
1000 secondEntry = secondEntry.substring(2);
1003 // Create a third entry if required.
1004 if (secondEntry.contains("*")) {
1005 wildcardIndex = secondEntry.indexOf("*");
1007 String thirdEntry = secondEntry.substring(wildcardIndex + 1);
1008 secondEntry = secondEntry.substring(0, wildcardIndex);
1010 String[] tripleEntry = {firstEntry, secondEntry, thirdEntry};
1012 multiEntryBlockList.add(tripleEntry);
1014 //Log.i("BlockLists", "Multi entry tripple block list added: " + firstEntry + " , " + secondEntry + " , " + thirdEntry);
1016 if (firstEntry.startsWith("|")) {
1017 String[] doubleEntry = {firstEntry.substring(1), secondEntry};
1019 multiEntryInitialBlockList.add(doubleEntry);
1021 //Log.i("BlockLists", "Multi entry initial block list added: " + firstEntry.substring(1) + " , " + secondEntry);
1022 } else if (firstEntry.startsWith("^")) {
1023 String firstEntryBase = firstEntry.substring(1);
1025 String firstEntry1 = ":" + firstEntryBase;
1026 String firstEntry2 = "/" + firstEntryBase;
1027 String firstEntry3 = "?" + firstEntryBase;
1028 String firstEntry4 = "=" + firstEntryBase;
1029 String firstEntry5 = "&" + firstEntryBase;
1031 String[] doubleEntry1 = {firstEntry1, secondEntry};
1032 String[] doubleEntry2 = {firstEntry2, secondEntry};
1033 String[] doubleEntry3 = {firstEntry3, secondEntry};
1034 String[] doubleEntry4 = {firstEntry4, secondEntry};
1035 String[] doubleEntry5 = {firstEntry5, secondEntry};
1037 multiEntryBlockList.add(doubleEntry1);
1038 multiEntryBlockList.add(doubleEntry2);
1039 multiEntryBlockList.add(doubleEntry3);
1040 multiEntryBlockList.add(doubleEntry4);
1041 multiEntryBlockList.add(doubleEntry5);
1043 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry1 + " , " + secondEntry);
1044 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry2 + " , " + secondEntry);
1045 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry3 + " , " + secondEntry);
1046 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry4 + " , " + secondEntry);
1047 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry5 + " , " + secondEntry);
1048 } else if (secondEntry.startsWith("^")) {
1049 String secondEntryBase = secondEntry.substring(1);
1051 String secondEntry1 = ":" + secondEntryBase;
1052 String secondEntry2 = "/" + secondEntryBase;
1053 String secondEntry3 = "?" + secondEntryBase;
1054 String secondEntry4 = "=" + secondEntryBase;
1055 String secondEntry5 = "&" + secondEntryBase;
1057 String[] doubleEntry1 = {firstEntry, secondEntry1};
1058 String[] doubleEntry2 = {firstEntry, secondEntry2};
1059 String[] doubleEntry3 = {firstEntry, secondEntry3};
1060 String[] doubleEntry4 = {firstEntry, secondEntry4};
1061 String[] doubleEntry5 = {firstEntry, secondEntry5};
1063 multiEntryBlockList.add(doubleEntry1);
1064 multiEntryBlockList.add(doubleEntry2);
1065 multiEntryBlockList.add(doubleEntry3);
1066 multiEntryBlockList.add(doubleEntry4);
1067 multiEntryBlockList.add(doubleEntry5);
1069 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry1);
1070 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry2);
1071 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry3);
1072 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry4);
1073 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry5);
1074 } else if (secondEntry.endsWith("^")) {
1075 String secondEntryBase = secondEntry.substring(0, secondEntry.length() - 1);
1077 String secondEntry1 = secondEntryBase + ":";
1078 String secondEntry2 = secondEntryBase + "/";
1079 String secondEntry3 = secondEntryBase + "?";
1080 String secondEntry4 = secondEntryBase + "=";
1081 String secondEntry5 = secondEntryBase + "&";
1083 String[] doubleEntry1 = {firstEntry, secondEntry1};
1084 String[] doubleEntry2 = {firstEntry, secondEntry2};
1085 String[] doubleEntry3 = {firstEntry, secondEntry3};
1086 String[] doubleEntry4 = {firstEntry, secondEntry4};
1087 String[] doubleEntry5 = {firstEntry, secondEntry5};
1089 String[] doubleEntryFinal = {firstEntry, secondEntryBase};
1091 multiEntryBlockList.add(doubleEntry1);
1092 multiEntryBlockList.add(doubleEntry2);
1093 multiEntryBlockList.add(doubleEntry3);
1094 multiEntryBlockList.add(doubleEntry4);
1095 multiEntryBlockList.add(doubleEntry5);
1097 multiEntryFinalBlockList.add(doubleEntryFinal);
1099 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry1);
1100 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry2);
1101 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry3);
1102 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry4);
1103 //Log.i("BlockLists", "Multi entry ^ block list added: " + firstEntry + " , " + secondEntry5);
1105 //Log.i("BlockLists", "Multi entry final block list added: " + firstEntry + " , " + secondEntryBase);
1107 String[] doubleEntry = {firstEntry, secondEntry};
1109 multiEntryBlockList.add(doubleEntry);
1111 //Log.i("BlockLists", "Multi entry block list added: " + firstEntry + " , " + secondEntry);
1115 if (blockListEntry.endsWith("^")) { // `^` matches against `:`, `/`, `?`, `=`, `&`, and the end of the URL.
1116 // Add all the variations to the main block list.
1117 mainBlockList.add(blockListEntry.substring(0, blockListEntry.length() - 1) + ":");
1118 mainBlockList.add(blockListEntry.substring(0, blockListEntry.length() - 1) + "/");
1119 mainBlockList.add(blockListEntry.substring(0, blockListEntry.length() - 1) + "?");
1120 mainBlockList.add(blockListEntry.substring(0, blockListEntry.length() - 1) + "=");
1121 mainBlockList.add(blockListEntry.substring(0, blockListEntry.length() - 1) + "&");
1123 // Add the base block entry to the final block list.
1124 finalBlockList.add(blockListEntry.substring(0, blockListEntry.length() - 1));
1126 //Log.i("BlockLists", "Main block list added: " + blockListEntry.substring(0, blockListEntry.length() - 1) + ":");
1127 //Log.i("BlockLists", "Main block list added: " + blockListEntry.substring(0, blockListEntry.length() - 1) + "/");
1128 //Log.i("BlockLists", "Main block list added: " + blockListEntry.substring(0, blockListEntry.length() - 1) + "?");
1129 //Log.i("BlockLists", "Main block list added: " + blockListEntry.substring(0, blockListEntry.length() - 1) + "=");
1130 //Log.i("BlockLists", "Main block list added: " + blockListEntry.substring(0, blockListEntry.length() - 1) + "&");
1131 //Log.i("BlockLists", "Final block list added: " + blockListEntry.substring(0, blockListEntry.length() - 1));
1132 } else { // This is a basic entry.
1133 // Add the modified block list entry to the main block list.
1134 mainBlockList.add(blockListEntry);
1136 //Log.i("BlockLists", "Main block list added: " + blockListEntry);
1142 // Close `bufferedReader`.
1143 bufferedReader.close();
1144 } catch (IOException e) {
1145 // The asset exists, so the `IOException` will never be thrown.
1148 Log.i("BlockLists", "Finish populating block lists");
1150 // Set the content view.
1151 setContentView(R.layout.main_drawerlayout);
1153 // Get a handle for `inputMethodManager`.
1154 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
1156 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
1157 supportAppBar = findViewById(R.id.app_bar);
1158 setSupportActionBar(supportAppBar);
1159 appBar = getSupportActionBar();
1161 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
1162 assert appBar != null;
1164 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
1165 appBar.setCustomView(R.layout.url_app_bar);
1166 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
1168 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
1169 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
1170 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
1171 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
1173 // Get a handle for `urlTextBox`.
1174 urlTextBox = findViewById(R.id.url_edittext);
1176 // Remove the formatting from `urlTextBar` when the user is editing the text.
1177 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
1178 if (hasFocus) { // The user is editing `urlTextBox`.
1179 // Remove the highlighting.
1180 urlTextBox.getText().removeSpan(redColorSpan);
1181 urlTextBox.getText().removeSpan(initialGrayColorSpan);
1182 urlTextBox.getText().removeSpan(finalGrayColorSpan);
1183 } else { // The user has stopped editing `urlTextBox`.
1184 // Reapply the highlighting.
1189 // Set the go button on the keyboard to load the URL in `urlTextBox`.
1190 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
1191 // If the event is a key-down event on the `enter` button, load the URL.
1192 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
1193 // Load the URL into the mainWebView and consume the event.
1195 loadUrlFromTextBox();
1196 } catch (UnsupportedEncodingException e) {
1197 e.printStackTrace();
1199 // If the enter key was pressed, consume the event.
1202 // If any other key was pressed, do not consume the event.
1207 // Set `waitingForOrbotHTMLString`.
1208 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
1210 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
1211 currentDomainName = "";
1212 orbotStatus = "unknown";
1213 waitingForOrbot = false;
1215 // Create an Orbot status `BroadcastReceiver`.
1216 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
1218 public void onReceive(Context context, Intent intent) {
1219 // Store the content of the status message in `orbotStatus`.
1220 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
1222 // If we are waiting on Orbot, load the website now that Orbot is connected.
1223 if (orbotStatus.equals("ON") && waitingForOrbot) {
1224 // Reset `waitingForOrbot`.
1225 waitingForOrbot = false;
1227 // Load `formattedUrlString
1228 loadUrl(formattedUrlString);
1233 // Register `orbotStatusBroadcastReceiver` on `this` context.
1234 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
1236 // Get handles for views that need to be accessed.
1237 drawerLayout = findViewById(R.id.drawerlayout);
1238 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
1239 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
1240 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
1241 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
1242 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
1243 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
1244 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
1245 mainWebView = findViewById(R.id.main_webview);
1246 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1247 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1248 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
1249 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
1250 favoriteIconImageView = findViewById(R.id.favorite_icon);
1252 // 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.
1254 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
1255 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
1256 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
1257 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
1259 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
1260 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
1261 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
1262 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
1265 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
1266 launchBookmarksActivityFab.setOnClickListener(v -> {
1267 // Create an intent to launch the bookmarks activity.
1268 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
1270 // Include the current folder with the `Intent`.
1271 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
1274 startActivity(bookmarksIntent);
1277 // Set the create new bookmark folder FAB to display the `AlertDialog`.
1278 createBookmarkFolderFab.setOnClickListener(v -> {
1279 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
1280 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
1281 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
1284 // Set the create new bookmark FAB to display the `AlertDialog`.
1285 createBookmarkFab.setOnClickListener(view -> {
1286 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
1287 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
1288 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
1291 // Create a double-tap listener to toggle full-screen mode.
1292 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
1293 // Override `onDoubleTap()`. All other events are handled using the default settings.
1295 public boolean onDoubleTap(MotionEvent event) {
1296 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
1297 // Toggle `inFullScreenBrowsingMode`.
1298 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
1300 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
1301 // Hide the `appBar`.
1304 // Hide the `BannerAd` in the free flavor.
1305 if (BuildConfig.FLAVOR.contentEquals("free")) {
1306 BannerAd.hideAd(adView);
1309 // Modify the system bars.
1310 if (hideSystemBarsOnFullscreen) { // Hide everything.
1311 // Remove the translucent overlays.
1312 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1314 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1315 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1317 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1318 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1319 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1321 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1323 // Set `rootCoordinatorLayout` to fill the whole screen.
1324 rootCoordinatorLayout.setFitsSystemWindows(false);
1325 } else { // Hide everything except the status and navigation bars.
1326 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
1327 rootCoordinatorLayout.setFitsSystemWindows(false);
1329 // 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.
1330 if (translucentNavigationBarOnFullscreen) {
1331 // Set the navigation bar to be translucent.
1332 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1335 } else { // Switch to normal viewing mode.
1336 // Show the `appBar`.
1339 // Show the `BannerAd` in the free flavor.
1340 if (BuildConfig.FLAVOR.contentEquals("free")) {
1341 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1342 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1344 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1345 adView = findViewById(R.id.adview);
1348 // Remove the translucent navigation bar flag if it is set.
1349 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1351 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1352 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1354 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1355 rootCoordinatorLayout.setSystemUiVisibility(0);
1357 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1358 rootCoordinatorLayout.setFitsSystemWindows(true);
1361 // Consume the double-tap.
1363 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
1369 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
1370 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
1371 // Call `performClick()` on the view, which is required for accessibility.
1374 // Send the `event` to `gestureDetector`.
1375 return gestureDetector.onTouchEvent(event);
1378 // Update `findOnPageCountTextView`.
1379 mainWebView.setFindListener(new WebView.FindListener() {
1380 // Get a handle for `findOnPageCountTextView`.
1381 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
1384 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
1385 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
1386 // Set `findOnPageCountTextView` to `0/0`.
1387 findOnPageCountTextView.setText(R.string.zero_of_zero);
1388 } else if (isDoneCounting) { // There are matches.
1389 // `activeMatchOrdinal` is zero-based.
1390 int activeMatch = activeMatchOrdinal + 1;
1392 // Build the match string.
1393 String matchString = activeMatch + "/" + numberOfMatches;
1395 // Set `findOnPageCountTextView`.
1396 findOnPageCountTextView.setText(matchString);
1401 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
1402 findOnPageEditText.addTextChangedListener(new TextWatcher() {
1404 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1409 public void onTextChanged(CharSequence s, int start, int before, int count) {
1414 public void afterTextChanged(Editable s) {
1415 // Search for the text in `mainWebView`.
1416 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
1420 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
1421 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
1422 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
1423 // Hide the soft keyboard. `0` indicates no additional flags.
1424 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1426 // Consume the event.
1428 } else { // A different key was pressed.
1429 // Do not consume the event.
1434 // Implement swipe to refresh
1435 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
1436 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
1437 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
1439 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
1440 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
1441 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
1443 // Listen for touches on the navigation menu.
1444 final NavigationView navigationView = findViewById(R.id.navigationview);
1445 navigationView.setNavigationItemSelectedListener(this);
1447 // 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.
1448 final Menu navigationMenu = navigationView.getMenu();
1449 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
1450 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
1451 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
1453 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
1454 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
1455 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
1457 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
1458 currentBookmarksFolder = "";
1460 // Load the home folder, which is `""` in the database.
1461 loadBookmarksFolder();
1463 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
1464 // Convert the id from long to int to match the format of the bookmarks database.
1465 int databaseID = (int) id;
1467 // Get the bookmark `Cursor` for this ID and move it to the first row.
1468 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
1469 bookmarkCursor.moveToFirst();
1471 // Act upon the bookmark according to the type.
1472 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
1473 // Store the new folder name in `currentBookmarksFolder`.
1474 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
1476 // Load the new folder.
1477 loadBookmarksFolder();
1478 } else { // The selected bookmark is not a folder.
1479 // Load the bookmark URL.
1480 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
1482 // Close the bookmarks drawer.
1483 drawerLayout.closeDrawer(GravityCompat.END);
1486 // Close the `Cursor`.
1487 bookmarkCursor.close();
1490 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
1491 // Convert the database ID from `long` to `int`.
1492 int databaseId = (int) id;
1494 // Find out if the selected bookmark is a folder.
1495 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
1498 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
1499 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
1501 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
1502 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
1503 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
1505 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
1506 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
1507 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
1510 // Consume the event.
1514 // The `DrawerListener` allows us to update the Navigation Menu.
1515 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
1517 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
1521 public void onDrawerOpened(@NonNull View drawerView) {
1525 public void onDrawerClosed(@NonNull View drawerView) {
1529 public void onDrawerStateChanged(int newState) {
1530 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
1531 // Update the `Back`, `Forward`, and `History` menu items.
1532 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
1533 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
1534 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
1536 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
1537 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1539 // Clear the focus from `urlTextBox` if it has it.
1540 urlTextBox.clearFocus();
1545 // drawerToggle creates the hamburger icon at the start of the AppBar.
1546 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
1548 mainWebView.setWebViewClient(new WebViewClient() {
1549 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1550 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
1551 @SuppressWarnings("deprecation")
1553 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1554 if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1555 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1556 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1558 // Parse the url and set it as the data for the `Intent`.
1559 emailIntent.setData(Uri.parse(url));
1561 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1562 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1565 startActivity(emailIntent);
1567 // Returning `true` indicates the application is handling the URL.
1569 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1570 // `ACTION_DIAL` open the dialer and loads the phone number, but waits for the user to place the call.
1571 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1573 // Add the phone number to the intent.
1574 dialIntent.setData(Uri.parse(url));
1576 // `FLAG_ACTIVITY_NEW_TASK` opens the dialer in a new task instead as part of Privacy Browser.
1577 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1580 startActivity(dialIntent);
1582 // Returning `true` indicates the application is handling the URL.
1584 } else { // Load the URL in Privacy Browser.
1585 // Apply the domain settings for the new URL.
1586 applyDomainSettings(url);
1588 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
1593 // Check requests against the block lists. The deprecated `shouldInterceptRequest` must be used until minimum API >= 21.
1594 @SuppressWarnings("deprecation")
1596 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1597 if (adBlockerEnabled) { // Check the block lists.
1598 Log.i("BlockLists", "Begin check for " + url);
1600 Uri uri = Uri.parse(url);
1601 String domain = uri.getHost();
1603 for (String whiteListEntry : mainWhiteList) {
1604 if (url.contains(whiteListEntry)) {
1605 Log.i("BlockLists", "Request allowed by main white list: " + whiteListEntry + " | " + url);
1607 // `Return null` loads the requested resource.
1612 for (String[] whiteListEntry : multiEntryWhiteList) {
1613 if (whiteListEntry.length == 2) { // There are two entries.
1614 if (url.contains(whiteListEntry[0]) && url.contains(whiteListEntry[1])) {
1615 Log.i("BlockLists", "Request allowed by multi entry white list: " + whiteListEntry[0] + " , " + whiteListEntry[1] + " | " + url);
1617 // `Return null` loads the requested resource.
1620 } else { // There are three entries.
1621 if (url.contains(whiteListEntry[0]) && url.contains(whiteListEntry[1]) && url.contains(whiteListEntry[2])) {
1622 Log.i("BlockLists", "Request allowed by multi entry white list: " + whiteListEntry[0] + " , " + whiteListEntry[1] + " , " + whiteListEntry[2] + " | " + url);
1624 // `Return null` loads the requested resource.
1630 for (String blockListEntry : mainBlockList) {
1631 if (url.contains(blockListEntry)) {
1632 Log.i("BlockLists", "Request blocked by main block list: " + blockListEntry + " | " + url);
1634 // Return an empty `WebResourceResponse`.
1635 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1639 for (String blockListEntry : initialBlockList) {
1640 if (url.startsWith(blockListEntry)) {
1641 Log.i("BlockLists", "Request blocked by initial block list: " + blockListEntry + " | " + url);
1643 // Return an empty `WebResourceResponse`.
1644 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1648 for (String blockListEntry : finalBlockList) {
1649 if (url.endsWith(blockListEntry)) {
1650 Log.i("BlockLists", "Request blocked by final block list: " + blockListEntry + " | " + url);
1652 // Return an empty `WebResourceResponse`.
1653 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1657 for (String[] blockListEntry : multiEntryBlockList) {
1658 if (blockListEntry.length == 2) { // There are two entries.
1659 if (url.contains(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1660 Log.i("BlockLists", "Request blocked by multi entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1662 // Return an empty `WebResourceResponse`.
1663 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1665 } else { // There are three entries.
1666 if (url.contains(blockListEntry[0]) && url.contains(blockListEntry[1]) && url.contains(blockListEntry[2])) {
1667 Log.i("BlockLists", "Request blocked by multi entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " , " + blockListEntry[2] + " | " + url);
1669 // Return an empty `WebResourceResponse`.
1670 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1675 for (String[] blockListEntry : multiEntryInitialBlockList) {
1676 if (url.startsWith(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1677 Log.i("BlockLists", "Request blocked by multi entry initial block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1679 // Return an empty `WebResourceResponse`.
1680 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1684 for (String[] blockListEntry : multiEntryFinalBlockList) {
1685 if (url.contains(blockListEntry[0]) && url.endsWith(blockListEntry[1])) {
1686 Log.i("BlockLists", "Request blocked by multi entry final block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1688 // Return an empty `WebResourceResponse`.
1689 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1693 for (String[] blockListEntry : domainBlockList) {
1694 if (domain.endsWith(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1695 Log.i("BlockLists", "Request blocked by domain block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1697 // Return an empty `WebResourceResponse`.
1698 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1702 for (String[] blockListEntry : domainInitialBlockList) {
1703 if (domain.endsWith(blockListEntry[0]) && url.startsWith(blockListEntry[1])) {
1704 Log.i("BlockLists", "Request blocked by domain initial block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1706 // Return an empty `WebResourceResponse`.
1707 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1711 for (String[] blockListEntry : domainFinalBlockList) {
1712 if (domain.endsWith(blockListEntry[0]) && url.endsWith(blockListEntry[2])) {
1713 Log.i("BlockLists", "Request blocked by domain final block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1715 // Return an empty `WebResourceResponse`.
1716 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1720 for (String[] blockListEntry : domainMultiEntryBlockList) {
1721 if (domain.endsWith(blockListEntry[0]) && url.contains(blockListEntry[1]) && url.contains(blockListEntry[2])) {
1722 Log.i("BlockLists", "Request blocked by domain multi entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " , " + blockListEntry[2] + " | " + url);
1724 // Return an empty `WebResourceResponse`.
1725 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1729 for (String[] blockListEntry : domainRegularExpressionBlockList) {
1730 if (domain.endsWith(blockListEntry[0]) && Pattern.matches(blockListEntry[1], url)) {
1731 Log.i("BlockLists", "Request blocked by domain regular expression block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1733 // Return an empty `WebResourceResponse`.
1734 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1738 for (String blockListEntry : regularExpressionBlockList) {
1739 if (Pattern.matches(blockListEntry, url)) {
1740 Log.i("BlockLists", "Request blocked by regular expression block list: " + blockListEntry + " | " + url);
1742 // Return an empty `WebResourceResponse`.
1743 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1747 Log.i("BlockLists", "End check for " + url);
1749 // `return null` loads the requested resource.
1751 } else { // Ad blocking is disabled.
1752 // `return null` loads the requested resource.
1757 // Handle HTTP authentication requests.
1759 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1760 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1761 httpAuthHandler = handler;
1763 // Display the HTTP authentication dialog.
1764 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1765 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1768 // Update the URL in urlTextBox when the page starts to load.
1770 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1771 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1773 mainWebView.setVisibility(View.INVISIBLE);
1776 // Hide the keyboard. `0` indicates no additional flags.
1777 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1779 // Check to see if we are waiting on Orbot.
1780 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1781 // 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.
1782 formattedUrlString = url;
1784 // Display the formatted URL text.
1785 urlTextBox.setText(formattedUrlString);
1787 // Apply text highlighting to `urlTextBox`.
1790 // Apply any custom domain settings if the URL was loaded by navigating history.
1791 if (navigatingHistory) {
1792 applyDomainSettings(url);
1795 // 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.
1796 urlIsLoading = true;
1800 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1802 public void onPageFinished(WebView view, String url) {
1803 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1804 urlIsLoading = false;
1806 // Clear the cache and history if Incognito Mode is enabled.
1807 if (incognitoModeEnabled) {
1808 // Clear the cache. `true` includes disk files.
1809 mainWebView.clearCache(true);
1811 // Clear the back/forward history.
1812 mainWebView.clearHistory();
1814 // Manually delete cache folders.
1816 // Delete the main `cache` folder.
1817 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1819 // 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`.
1820 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1821 } catch (IOException e) {
1822 // Do nothing if an error is thrown.
1826 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1827 if (!waitingForOrbot) {
1828 // Check to see if `WebView` has set `url` to be `about:blank`.
1829 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1830 // Set `formattedUrlString` to `""`.
1831 formattedUrlString = "";
1833 urlTextBox.setText(formattedUrlString);
1835 // Request focus for `urlTextBox`.
1836 urlTextBox.requestFocus();
1838 // Display the keyboard.
1839 inputMethodManager.showSoftInput(urlTextBox, 0);
1841 // Apply the domain settings. This clears any settings from the previous domain.
1842 applyDomainSettings(formattedUrlString);
1843 } else { // `WebView` has loaded a webpage.
1844 // Set `formattedUrlString`.
1845 formattedUrlString = url;
1847 // Only update `urlTextBox` if the user is not typing in it.
1848 if (!urlTextBox.hasFocus()) {
1849 // Display the formatted URL text.
1850 urlTextBox.setText(formattedUrlString);
1852 // Apply text highlighting to `urlTextBox`.
1857 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1858 sslCertificate = mainWebView.getCertificate();
1860 // 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.
1861 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1862 // Initialize the current SSL certificate variables.
1863 String currentWebsiteIssuedToCName = "";
1864 String currentWebsiteIssuedToOName = "";
1865 String currentWebsiteIssuedToUName = "";
1866 String currentWebsiteIssuedByCName = "";
1867 String currentWebsiteIssuedByOName = "";
1868 String currentWebsiteIssuedByUName = "";
1869 Date currentWebsiteSslStartDate = null;
1870 Date currentWebsiteSslEndDate = null;
1873 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1874 if (sslCertificate != null) {
1875 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1876 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1877 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1878 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1879 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1880 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1881 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1882 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1885 // 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`.
1886 String currentWebsiteSslStartDateString = "";
1887 String currentWebsiteSslEndDateString = "";
1888 String pinnedDomainSslStartDateString = "";
1889 String pinnedDomainSslEndDateString = "";
1891 // Convert the `Dates` to `Strings` if they are not `null`.
1892 if (currentWebsiteSslStartDate != null) {
1893 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1896 if (currentWebsiteSslEndDate != null) {
1897 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1900 if (pinnedDomainSslStartDate != null) {
1901 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1904 if (pinnedDomainSslEndDate != null) {
1905 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1908 // Check to see if the pinned SSL certificate matches the current website certificate.
1909 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1910 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1911 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1912 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1913 // The pinned SSL certificate doesn't match the current domain certificate.
1914 //Display the pinned SSL certificate mismatch `AlertDialog`.
1915 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1916 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1922 // Handle SSL Certificate errors.
1924 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1925 // Get the current website SSL certificate.
1926 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1928 // Extract the individual pieces of information from the current website SSL certificate.
1929 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1930 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1931 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1932 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1933 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1934 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1935 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1936 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1938 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1939 if (pinnedDomainSslCertificate &&
1940 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1941 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1942 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1943 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1944 // An SSL certificate is pinned and matches the current domain certificate.
1945 // Proceed to the website without displaying an error.
1947 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1948 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1949 sslErrorHandler = handler;
1951 // Display the SSL error `AlertDialog`.
1952 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1953 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1958 // Get a handle for the progress bar.
1959 final ProgressBar progressBar = findViewById(R.id.progress_bar);
1961 mainWebView.setWebChromeClient(new WebChromeClient() {
1962 // Update the progress bar when a page is loading.
1964 public void onProgressChanged(WebView view, int progress) {
1965 // Inject the night mode CSS if night mode is enabled.
1967 // `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
1968 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
1969 // `border: none` removes all borders, which can also be used to underline text.
1970 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
1971 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
1972 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
1973 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
1974 // Initialize a `Handler` to display `mainWebView`.
1975 Handler displayWebViewHandler = new Handler();
1977 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
1978 Runnable displayWebViewRunnable = () -> {
1979 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
1980 if (progressBar.getVisibility() == View.GONE) {
1981 mainWebView.setVisibility(View.VISIBLE);
1985 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
1986 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
1990 // Update the progress bar.
1991 progressBar.setProgress(progress);
1993 // Set the visibility of the progress bar.
1994 if (progress < 100) {
1995 // Show the progress bar.
1996 progressBar.setVisibility(View.VISIBLE);
1998 // Hide the progress bar.
1999 progressBar.setVisibility(View.GONE);
2001 // Display `mainWebView` if night mode is disabled.
2002 // 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
2003 // currently enabled.
2005 mainWebView.setVisibility(View.VISIBLE);
2008 //Stop the `SwipeToRefresh` indicator if it is running
2009 swipeRefreshLayout.setRefreshing(false);
2013 // Set the favorite icon when it changes.
2015 public void onReceivedIcon(WebView view, Bitmap icon) {
2016 // Only update the favorite icon if the website has finished loading.
2017 if (progressBar.getVisibility() == View.GONE) {
2018 // Save a copy of the favorite icon.
2019 favoriteIconBitmap = icon;
2021 // Place the favorite icon in the appBar.
2022 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
2026 // Save a copy of the title when it changes.
2028 public void onReceivedTitle(WebView view, String title) {
2029 // Save a copy of the title.
2030 webViewTitle = title;
2033 // Enter full screen video
2035 public void onShowCustomView(View view, CustomViewCallback callback) {
2036 // Pause the ad if this is the free flavor.
2037 if (BuildConfig.FLAVOR.contentEquals("free")) {
2038 BannerAd.pauseAd(adView);
2041 // Remove the translucent overlays.
2042 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2044 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2045 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2047 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2048 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2049 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2051 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2053 // Set `rootCoordinatorLayout` to fill the entire screen.
2054 rootCoordinatorLayout.setFitsSystemWindows(false);
2056 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
2057 fullScreenVideoFrameLayout.addView(view);
2058 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
2061 // Exit full screen video
2062 public void onHideCustomView() {
2063 // Hide `fullScreenVideoFrameLayout`.
2064 fullScreenVideoFrameLayout.removeAllViews();
2065 fullScreenVideoFrameLayout.setVisibility(View.GONE);
2067 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2068 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2070 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
2071 rootCoordinatorLayout.setFitsSystemWindows(true);
2073 // Show the ad if this is the free flavor.
2074 if (BuildConfig.FLAVOR.contentEquals("free")) {
2075 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2076 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2078 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2079 adView = findViewById(R.id.adview);
2084 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
2085 registerForContextMenu(mainWebView);
2087 // Allow the downloading of files.
2088 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
2089 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
2090 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
2091 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2094 // Allow pinch to zoom.
2095 mainWebView.getSettings().setBuiltInZoomControls(true);
2097 // Hide zoom controls.
2098 mainWebView.getSettings().setDisplayZoomControls(false);
2100 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
2101 mainWebView.getSettings().setUseWideViewPort(true);
2103 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
2104 mainWebView.getSettings().setLoadWithOverviewMode(true);
2106 // Explicitly disable geolocation.
2107 mainWebView.getSettings().setGeolocationEnabled(false);
2109 // Initialize cookieManager.
2110 cookieManager = CookieManager.getInstance();
2112 // 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).
2113 customHeaders.put("X-Requested-With", "");
2115 // 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.
2116 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
2118 // Get the intent that started the app.
2119 final Intent launchingIntent = getIntent();
2121 // Extract the launching intent data as `launchingIntentUriData`.
2122 final Uri launchingIntentUriData = launchingIntent.getData();
2124 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
2125 if (launchingIntentUriData != null) {
2126 formattedUrlString = launchingIntentUriData.toString();
2129 // Get a handle for the `Runtime`.
2130 privacyBrowserRuntime = Runtime.getRuntime();
2132 // Store the application's private data directory.
2133 privateDataDirectoryString = getApplicationInfo().dataDir;
2134 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
2136 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
2137 inFullScreenBrowsingMode = false;
2139 // Initialize AdView for the free flavor.
2140 adView = findViewById(R.id.adview);
2142 // Initialize the privacy settings variables.
2143 javaScriptEnabled = false;
2144 firstPartyCookiesEnabled = false;
2145 thirdPartyCookiesEnabled = false;
2146 domStorageEnabled = false;
2147 saveFormDataEnabled = false;
2150 // Initialize `webViewTitle`.
2151 webViewTitle = getString(R.string.no_title);
2153 // Initialize `favoriteIconBitmap`. `ContextCompat` must be used until API >= 21.
2154 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
2155 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
2156 assert favoriteIconBitmapDrawable != null;
2157 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
2159 // If the favorite icon is null, load the default.
2160 if (favoriteIconBitmap == null) {
2161 favoriteIconBitmap = favoriteIconDefaultBitmap;
2164 // Apply the app settings from the shared preferences.
2167 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
2168 if (!waitingForOrbot) {
2169 loadUrl(formattedUrlString);
2174 protected void onNewIntent(Intent intent) {
2175 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
2178 if (intent.getData() != null) {
2179 // Get the intent data and convert it to a string.
2180 final Uri intentUriData = intent.getData();
2181 formattedUrlString = intentUriData.toString();
2184 // Close the navigation drawer if it is open.
2185 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2186 drawerLayout.closeDrawer(GravityCompat.START);
2189 // Load the website.
2190 loadUrl(formattedUrlString);
2192 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
2193 mainWebView.requestFocus();
2197 public void onRestart() {
2198 // Run the default commands.
2201 // Apply the app settings, which may have been changed in `SettingsActivity`.
2204 // Apply the domain settings if returning from the Domains Activity.
2205 if (reapplyDomainSettingsOnRestart) {
2206 // Reset `reapplyDomainSettingsOnRestart`.
2207 reapplyDomainSettingsOnRestart = false;
2209 // Reapply the domain settings.
2210 applyDomainSettings(formattedUrlString);
2213 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2214 updatePrivacyIcons(true);
2216 // Set the display webpage images mode.
2217 setDisplayWebpageImages();
2219 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
2220 if (reloadOnRestart) {
2221 // Reload `mainWebView`.
2222 mainWebView.reload();
2224 // Reset `reloadOnRestartBoolean`.
2225 reloadOnRestart = false;
2228 // Load the URL on restart to apply changes to night mode.
2229 if (loadUrlOnRestart) {
2230 // Load the current `formattedUrlString`.
2231 loadUrl(formattedUrlString);
2233 // Reset `loadUrlOnRestart.
2234 loadUrlOnRestart = false;
2238 if (restartFromBookmarksActivity) {
2239 // Close the bookmarks drawer.
2240 drawerLayout.closeDrawer(GravityCompat.END);
2242 // Reload the bookmarks drawer.
2243 loadBookmarksFolder();
2245 // Reset `restartFromBookmarksActivity`.
2246 restartFromBookmarksActivity = false;
2250 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
2252 public void onResume() {
2253 // Run the default commands.
2256 // Resume JavaScript (if enabled).
2257 mainWebView.resumeTimers();
2259 // Resume `mainWebView`.
2260 mainWebView.onResume();
2262 // Resume the adView for the free flavor.
2263 if (BuildConfig.FLAVOR.contentEquals("free")) {
2264 BannerAd.resumeAd(adView);
2269 public void onPause() {
2270 // Pause `mainWebView`.
2271 mainWebView.onPause();
2273 // Stop all JavaScript.
2274 mainWebView.pauseTimers();
2276 // Pause the adView or it will continue to consume resources in the background on the free flavor.
2277 if (BuildConfig.FLAVOR.contentEquals("free")) {
2278 BannerAd.pauseAd(adView);
2285 public boolean onCreateOptionsMenu(Menu menu) {
2286 // Inflate the menu; this adds items to the action bar if it is present.
2287 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
2289 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
2292 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
2293 updatePrivacyIcons(false);
2295 // Get handles for the menu items.
2296 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2297 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2298 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2299 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
2301 // Only display third-party cookies if SDK >= 21
2302 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
2304 // Get the shared preference values. `this` references the current context.
2305 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2307 // Set the status of the additional app bar icons. The default is `false`.
2308 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
2309 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2310 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2311 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2312 } else { //Do not display the additional icons.
2313 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2314 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2315 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2322 public boolean onPrepareOptionsMenu(Menu menu) {
2323 // Get handles for the menu items.
2324 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2325 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2326 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2327 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2328 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
2329 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2330 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2331 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2332 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
2333 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2334 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2335 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
2337 // Set the text for the domain menu item.
2338 if (domainSettingsApplied) {
2339 addOrEditDomain.setTitle(R.string.edit_domain_settings);
2341 addOrEditDomain.setTitle(R.string.add_domain_settings);
2344 // Set the status of the menu item checkboxes.
2345 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2346 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2347 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2348 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
2349 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2351 // Enable third-party cookies if first-party cookies are enabled.
2352 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2354 // Enable `DOM Storage` if JavaScript is enabled.
2355 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2357 // Enable `Clear Cookies` if there are any.
2358 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2360 // Get a count of the number of files in the `Local Storage` directory.
2361 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2362 int localStorageDirectoryNumberOfFiles = 0;
2363 if (localStorageDirectory.exists()) {
2364 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2367 // Get a count of the number of files in the `IndexedDB` directory.
2368 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2369 int indexedDBDirectoryNumberOfFiles = 0;
2370 if (indexedDBDirectory.exists()) {
2371 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2374 // Enable `Clear DOM Storage` if there is any.
2375 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2377 // Enable `Clear Form Data` is there is any.
2378 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2379 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2381 // Enable `Clear Data` if any of the submenu items are enabled.
2382 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2384 // Initialize font size variables.
2385 int fontSize = mainWebView.getSettings().getTextZoom();
2386 String fontSizeTitle;
2387 MenuItem selectedFontSizeMenuItem;
2389 // Prepare the font size title and current size menu item.
2392 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2393 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2397 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2398 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2402 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2403 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2407 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2408 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2412 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2413 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2417 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2418 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2422 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2423 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2427 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2428 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2432 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2433 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2437 // Set the font size title and select the current size menu item.
2438 fontSizeMenuItem.setTitle(fontSizeTitle);
2439 selectedFontSizeMenuItem.setChecked(true);
2441 // Only show `Refresh` if `swipeToRefresh` is disabled.
2442 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
2444 // Run all the other default commands.
2445 super.onPrepareOptionsMenu(menu);
2447 // Display the menu.
2452 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2453 @SuppressLint("SetJavaScriptEnabled")
2454 // removeAllCookies is deprecated, but it is required for API < 21.
2455 @SuppressWarnings("deprecation")
2456 public boolean onOptionsItemSelected(MenuItem menuItem) {
2457 // Get the selected menu item ID.
2458 int menuItemId = menuItem.getItemId();
2460 // Set the commands that relate to the menu entries.
2461 switch (menuItemId) {
2462 case R.id.add_or_edit_domain:
2463 if (domainSettingsApplied) { // Edit the current domain settings.
2464 // Reapply the domain settings on returning to `MainWebViewActivity`.
2465 reapplyDomainSettingsOnRestart = true;
2466 currentDomainName = "";
2468 // Create an intent to launch the domains activity.
2469 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2471 // Put extra information instructing the domains activity to directly load the current domain.
2472 domainsIntent.putExtra("LoadDomain", domainSettingsDatabaseId);
2475 startActivity(domainsIntent);
2476 } else { // Add a new domain.
2477 // Show the add domain `AlertDialog`.
2478 AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
2479 addDomainDialog.show(getSupportFragmentManager(), getResources().getString(R.string.add_domain));
2483 case R.id.toggle_javascript:
2484 // Switch the status of javaScriptEnabled.
2485 javaScriptEnabled = !javaScriptEnabled;
2487 // Apply the new JavaScript status.
2488 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2490 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2491 updatePrivacyIcons(true);
2493 // Display a `Snackbar`.
2494 if (javaScriptEnabled) { // JavaScrip is enabled.
2495 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2496 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2497 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2498 } else { // Privacy mode.
2499 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2502 // Reload the WebView.
2503 mainWebView.reload();
2506 case R.id.toggle_first_party_cookies:
2507 // Switch the status of firstPartyCookiesEnabled.
2508 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2510 // Update the menu checkbox.
2511 menuItem.setChecked(firstPartyCookiesEnabled);
2513 // Apply the new cookie status.
2514 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2516 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2517 updatePrivacyIcons(true);
2519 // Display a `Snackbar`.
2520 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2521 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2522 } else if (javaScriptEnabled){ // JavaScript is still enabled.
2523 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2524 } else { // Privacy mode.
2525 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2528 // Reload the WebView.
2529 mainWebView.reload();
2532 case R.id.toggle_third_party_cookies:
2533 if (Build.VERSION.SDK_INT >= 21) {
2534 // Switch the status of thirdPartyCookiesEnabled.
2535 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2537 // Update the menu checkbox.
2538 menuItem.setChecked(thirdPartyCookiesEnabled);
2540 // Apply the new cookie status.
2541 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2543 // Display a `Snackbar`.
2544 if (thirdPartyCookiesEnabled) {
2545 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2547 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2550 // Reload the WebView.
2551 mainWebView.reload();
2552 } // Else do nothing because SDK < 21.
2555 case R.id.toggle_dom_storage:
2556 // Switch the status of domStorageEnabled.
2557 domStorageEnabled = !domStorageEnabled;
2559 // Update the menu checkbox.
2560 menuItem.setChecked(domStorageEnabled);
2562 // Apply the new DOM Storage status.
2563 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2565 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2566 updatePrivacyIcons(true);
2568 // Display a `Snackbar`.
2569 if (domStorageEnabled) {
2570 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2572 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2575 // Reload the WebView.
2576 mainWebView.reload();
2579 case R.id.toggle_save_form_data:
2580 // Switch the status of saveFormDataEnabled.
2581 saveFormDataEnabled = !saveFormDataEnabled;
2583 // Update the menu checkbox.
2584 menuItem.setChecked(saveFormDataEnabled);
2586 // Apply the new form data status.
2587 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2589 // Display a `Snackbar`.
2590 if (saveFormDataEnabled) {
2591 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2593 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2596 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2597 updatePrivacyIcons(true);
2599 // Reload the WebView.
2600 mainWebView.reload();
2603 case R.id.clear_cookies:
2604 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2605 .setAction(R.string.undo, v -> {
2606 // Do nothing because everything will be handled by `onDismissed()` below.
2608 .addCallback(new Snackbar.Callback() {
2610 public void onDismissed(Snackbar snackbar, int event) {
2612 // The user pushed the `Undo` button.
2613 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2617 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2619 // `cookieManager.removeAllCookie()` varies by SDK.
2620 if (Build.VERSION.SDK_INT < 21) {
2621 cookieManager.removeAllCookie();
2623 // `null` indicates no callback.
2624 cookieManager.removeAllCookies(null);
2632 case R.id.clear_dom_storage:
2633 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2634 .setAction(R.string.undo, v -> {
2635 // Do nothing because everything will be handled by `onDismissed()` below.
2637 .addCallback(new Snackbar.Callback() {
2639 public void onDismissed(Snackbar snackbar, int event) {
2641 // The user pushed the `Undo` button.
2642 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2646 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2648 // Delete the DOM Storage.
2649 WebStorage webStorage = WebStorage.getInstance();
2650 webStorage.deleteAllData();
2652 // Manually delete the DOM storage files and directories.
2654 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2655 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2657 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2658 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2659 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2660 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2661 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2662 } catch (IOException e) {
2663 // Do nothing if an error is thrown.
2671 case R.id.clear_form_data:
2672 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2673 .setAction(R.string.undo, v -> {
2674 // Do nothing because everything will be handled by `onDismissed()` below.
2676 .addCallback(new Snackbar.Callback() {
2678 public void onDismissed(Snackbar snackbar, int event) {
2680 // The user pushed the `Undo` button.
2681 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2685 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2687 // Delete the form data.
2688 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2689 mainWebViewDatabase.clearFormData();
2696 case R.id.font_size_twenty_five_percent:
2697 mainWebView.getSettings().setTextZoom(25);
2700 case R.id.font_size_fifty_percent:
2701 mainWebView.getSettings().setTextZoom(50);
2704 case R.id.font_size_seventy_five_percent:
2705 mainWebView.getSettings().setTextZoom(75);
2708 case R.id.font_size_one_hundred_percent:
2709 mainWebView.getSettings().setTextZoom(100);
2712 case R.id.font_size_one_hundred_twenty_five_percent:
2713 mainWebView.getSettings().setTextZoom(125);
2716 case R.id.font_size_one_hundred_fifty_percent:
2717 mainWebView.getSettings().setTextZoom(150);
2720 case R.id.font_size_one_hundred_seventy_five_percent:
2721 mainWebView.getSettings().setTextZoom(175);
2724 case R.id.font_size_two_hundred_percent:
2725 mainWebView.getSettings().setTextZoom(200);
2728 case R.id.display_images:
2729 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2730 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2731 mainWebView.reload();
2732 } else { // Images are not currently loaded automatically.
2733 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2736 // Set `onTheFlyDisplayImagesSet`.
2737 onTheFlyDisplayImagesSet = true;
2741 // Setup the share string.
2742 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2744 // Create the share intent.
2745 Intent shareIntent = new Intent();
2746 shareIntent.setAction(Intent.ACTION_SEND);
2747 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2748 shareIntent.setType("text/plain");
2751 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2754 case R.id.find_on_page:
2755 // Hide the URL app bar.
2756 supportAppBar.setVisibility(View.GONE);
2758 // Show the Find on Page `RelativeLayout`.
2759 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2761 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2762 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2763 findOnPageEditText.postDelayed(() -> {
2764 // Set the focus on `findOnPageEditText`.
2765 findOnPageEditText.requestFocus();
2767 // Display the keyboard. `0` sets no input flags.
2768 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2773 // Get a `PrintManager` instance.
2774 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2776 // Convert `mainWebView` to `printDocumentAdapter`.
2777 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2779 // Remove the lint error below that `printManager` might be `null`.
2780 assert printManager != null;
2782 // Print the document. The print attributes are `null`.
2783 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2786 case R.id.view_source:
2787 // Launch the Vew Source activity.
2788 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2789 startActivity(viewSourceIntent);
2792 case R.id.add_to_homescreen:
2793 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2794 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2795 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2797 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2801 mainWebView.reload();
2805 // Don't consume the event.
2806 return super.onOptionsItemSelected(menuItem);
2810 // removeAllCookies is deprecated, but it is required for API < 21.
2811 @SuppressWarnings("deprecation")
2813 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2814 int menuItemId = menuItem.getItemId();
2816 switch (menuItemId) {
2822 if (mainWebView.canGoBack()) {
2823 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2824 navigatingHistory = true;
2826 // Load the previous website in the history.
2827 mainWebView.goBack();
2832 if (mainWebView.canGoForward()) {
2833 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2834 navigatingHistory = true;
2836 // Load the next website in the history.
2837 mainWebView.goForward();
2842 // Get the `WebBackForwardList`.
2843 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2845 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2846 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2847 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2850 case R.id.downloads:
2851 // Launch the system Download Manager.
2852 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2854 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2855 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2857 startActivity(downloadManagerIntent);
2861 // Reapply the domain settings on returning to `MainWebViewActivity`.
2862 reapplyDomainSettingsOnRestart = true;
2863 currentDomainName = "";
2865 // Launch `DomainsActivity`.
2866 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2867 startActivity(domainsIntent);
2871 // Reapply the domain settings on returning to `MainWebViewActivity`.
2872 reapplyDomainSettingsOnRestart = true;
2873 currentDomainName = "";
2875 // Launch `SettingsActivity`.
2876 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2877 startActivity(settingsIntent);
2881 // Launch `GuideActivity`.
2882 Intent guideIntent = new Intent(this, GuideActivity.class);
2883 startActivity(guideIntent);
2887 // Launch `AboutActivity`.
2888 Intent aboutIntent = new Intent(this, AboutActivity.class);
2889 startActivity(aboutIntent);
2892 case R.id.clearAndExit:
2893 // Get a handle for `sharedPreferences`. `this` references the current context.
2894 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2896 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2899 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2900 // The command to remove cookies changed slightly in API 21.
2901 if (Build.VERSION.SDK_INT >= 21) {
2902 cookieManager.removeAllCookies(null);
2904 cookieManager.removeAllCookie();
2907 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2909 // We have to use two commands because `Runtime.exec()` does not like `*`.
2910 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2911 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2912 } catch (IOException e) {
2913 // Do nothing if an error is thrown.
2917 // Clear DOM storage.
2918 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2919 // Ask `WebStorage` to clear the DOM storage.
2920 WebStorage webStorage = WebStorage.getInstance();
2921 webStorage.deleteAllData();
2923 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2925 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2926 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2928 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2929 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2930 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2931 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2932 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2933 } catch (IOException e) {
2934 // Do nothing if an error is thrown.
2939 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2940 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2941 webViewDatabase.clearFormData();
2943 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2945 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2946 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2947 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2948 } catch (IOException e) {
2949 // Do nothing if an error is thrown.
2954 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2955 // `true` includes disk files.
2956 mainWebView.clearCache(true);
2958 // Manually delete the cache directories.
2960 // Delete the main cache directory.
2961 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2962 // Delete the secondary `Service Worker` cache directory.
2963 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2964 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2965 } catch (IOException e) {
2966 // Do nothing if an error is thrown.
2970 // Clear SSL certificate preferences.
2971 mainWebView.clearSslPreferences();
2973 // Clear the back/forward history.
2974 mainWebView.clearHistory();
2976 // Clear `formattedUrlString`.
2977 formattedUrlString = null;
2979 // Clear `customHeaders`.
2980 customHeaders.clear();
2982 // Detach all views from `mainWebViewRelativeLayout`.
2983 mainWebViewRelativeLayout.removeAllViews();
2985 // Destroy the internal state of `mainWebView`.
2986 mainWebView.destroy();
2988 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2989 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2990 if (clearEverything) {
2992 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2993 } catch (IOException e) {
2994 // Do nothing if an error is thrown.
2998 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2999 if (Build.VERSION.SDK_INT >= 21) {
3000 finishAndRemoveTask();
3005 // Remove the terminated program from RAM. The status code is `0`.
3010 // Close the navigation drawer.
3011 drawerLayout.closeDrawer(GravityCompat.START);
3016 public void onPostCreate(Bundle savedInstanceState) {
3017 super.onPostCreate(savedInstanceState);
3019 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
3020 drawerToggle.syncState();
3024 public void onConfigurationChanged(Configuration newConfig) {
3025 super.onConfigurationChanged(newConfig);
3027 // Reload the ad for the free flavor if we are not in full screen mode.
3028 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
3030 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
3032 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3033 adView = findViewById(R.id.adview);
3036 // `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:
3037 // https://code.google.com/p/android/issues/detail?id=20493#c8
3038 // ActivityCompat.invalidateOptionsMenu(this);
3042 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
3043 // Store the `HitTestResult`.
3044 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
3047 final String imageUrl;
3048 final String linkUrl;
3050 // Get a handle for the `ClipboardManager`.
3051 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
3053 // Remove the lint errors below that `clipboardManager` might be `null`.
3054 assert clipboardManager != null;
3056 switch (hitTestResult.getType()) {
3057 // `SRC_ANCHOR_TYPE` is a link.
3058 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
3059 // Get the target URL.
3060 linkUrl = hitTestResult.getExtra();
3062 // Set the target URL as the title of the `ContextMenu`.
3063 menu.setHeaderTitle(linkUrl);
3065 // Add a `Load URL` entry.
3066 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
3071 // Add a `Copy URL` entry.
3072 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3073 // Save the link URL in a `ClipData`.
3074 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
3076 // Set the `ClipData` as the clipboard's primary clip.
3077 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
3081 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3082 menu.add(R.string.cancel);
3085 case WebView.HitTestResult.EMAIL_TYPE:
3086 // Get the target URL.
3087 linkUrl = hitTestResult.getExtra();
3089 // Set the target URL as the title of the `ContextMenu`.
3090 menu.setHeaderTitle(linkUrl);
3092 // Add a `Write Email` entry.
3093 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
3094 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
3095 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
3097 // Parse the url and set it as the data for the `Intent`.
3098 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
3100 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
3101 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3104 startActivity(emailIntent);
3108 // Add a `Copy Email Address` entry.
3109 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
3110 // Save the email address in a `ClipData`.
3111 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
3113 // Set the `ClipData` as the clipboard's primary clip.
3114 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
3118 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3119 menu.add(R.string.cancel);
3122 // `IMAGE_TYPE` is an image.
3123 case WebView.HitTestResult.IMAGE_TYPE:
3124 // Get the image URL.
3125 imageUrl = hitTestResult.getExtra();
3127 // Set the image URL as the title of the `ContextMenu`.
3128 menu.setHeaderTitle(imageUrl);
3130 // Add a `View Image` entry.
3131 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3136 // Add a `Download Image` entry.
3137 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3138 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
3139 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3140 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3144 // Add a `Copy URL` entry.
3145 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3146 // Save the image URL in a `ClipData`.
3147 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3149 // Set the `ClipData` as the clipboard's primary clip.
3150 clipboardManager.setPrimaryClip(srcImageTypeClipData);
3154 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3155 menu.add(R.string.cancel);
3159 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
3160 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
3161 // Get the image URL.
3162 imageUrl = hitTestResult.getExtra();
3164 // Set the image URL as the title of the `ContextMenu`.
3165 menu.setHeaderTitle(imageUrl);
3167 // Add a `View Image` entry.
3168 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3173 // Add a `Download Image` entry.
3174 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3175 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
3176 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3177 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3181 // Add a `Copy URL` entry.
3182 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3183 // Save the image URL in a `ClipData`.
3184 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3186 // Set the `ClipData` as the clipboard's primary clip.
3187 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3191 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3192 menu.add(R.string.cancel);
3198 public void onAddDomain(AppCompatDialogFragment dialogFragment) {
3199 // Reapply the domain settings on returning to `MainWebViewActivity`.
3200 reapplyDomainSettingsOnRestart = true;
3201 currentDomainName = "";
3203 // Get the new domain name `String` from `dialogFragment`.
3204 EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
3205 String domainNameString = domainNameEditText.getText().toString();
3207 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3208 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3209 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3211 // Create the domain and store the database ID in `currentDomainDatabaseId`.
3212 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
3214 // Create an intent to launch the domains activity.
3215 Intent domainsIntent = new Intent(this, DomainsActivity.class);
3217 // Put extra information instructing the domains activity to directly load the current domain.
3218 domainsIntent.putExtra("LoadDomain", newDomainDatabaseId);
3221 startActivity(domainsIntent);
3225 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3226 // Get the `EditTexts` from the `dialogFragment`.
3227 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3228 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3230 // Extract the strings from the `EditTexts`.
3231 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3232 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3234 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3235 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3236 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3237 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3239 // Display the new bookmark below the current items in the (0 indexed) list.
3240 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3242 // Create the bookmark.
3243 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3245 // Update `bookmarksCursor` with the current contents of this folder.
3246 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3248 // Update the `ListView`.
3249 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3251 // Scroll to the new bookmark.
3252 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3256 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3257 // Get handles for the views in `dialogFragment`.
3258 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3259 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3260 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3262 // Get new folder name string.
3263 String folderNameString = createFolderNameEditText.getText().toString();
3265 // Get the new folder icon `Bitmap`.
3266 Bitmap folderIconBitmap;
3267 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3268 // Get the default folder icon and convert it to a `Bitmap`.
3269 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3270 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3271 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3272 } else { // Use the `WebView` favorite icon.
3273 folderIconBitmap = favoriteIconBitmap;
3276 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3277 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3278 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3279 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3281 // Move all the bookmarks down one in the display order.
3282 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3283 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3284 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3287 // Create the folder, which will be placed at the top of the `ListView`.
3288 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3290 // Update `bookmarksCursor` with the current contents of this folder.
3291 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3293 // Update the `ListView`.
3294 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3296 // Scroll to the new folder.
3297 bookmarksListView.setSelection(0);
3301 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3302 // Get the shortcut name.
3303 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3304 String shortcutNameString = shortcutNameEditText.getText().toString();
3306 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3307 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3309 // Setup the shortcut intent.
3310 Intent shortcutIntent = new Intent();
3311 shortcutIntent.setAction(Intent.ACTION_VIEW);
3312 shortcutIntent.setData(Uri.parse(formattedUrlString));
3314 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3315 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3317 // Add the required fields to the shortcut info builder.
3318 shortcutInfoBuilder.setIcon(favoriteIcon);
3319 shortcutInfoBuilder.setIntent(shortcutIntent);
3320 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3322 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3323 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3327 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3328 // Download the image if it has an HTTP or HTTPS URI.
3329 if (imageUrl.startsWith("http")) {
3330 // Get a handle for the system `DOWNLOAD_SERVICE`.
3331 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3333 // Parse `imageUrl`.
3334 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3336 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3337 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3338 if (firstPartyCookiesEnabled) {
3339 // Get the cookies for `imageUrl`.
3340 String cookies = cookieManager.getCookie(imageUrl);
3342 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3343 downloadRequest.addRequestHeader("Cookie", cookies);
3346 // Get the file name from `dialogFragment`.
3347 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3348 String imageName = downloadImageNameEditText.getText().toString();
3350 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
3351 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
3352 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
3353 } else { // Only set the title using `imageName`.
3354 downloadRequest.setTitle(imageName);
3357 // Allow `MediaScanner` to index the download if it is a media file.
3358 downloadRequest.allowScanningByMediaScanner();
3360 // Add the URL as the description for the download.
3361 downloadRequest.setDescription(imageUrl);
3363 // Show the download notification after the download is completed.
3364 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3366 // Remove the lint warning below that `downloadManager` might be `null`.
3367 assert downloadManager != null;
3369 // Initiate the download.
3370 downloadManager.enqueue(downloadRequest);
3371 } else { // The image is not an HTTP or HTTPS URI.
3372 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3377 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3378 // Download the file if it has an HTTP or HTTPS URI.
3379 if (downloadUrl.startsWith("http")) {
3381 // Get a handle for the system `DOWNLOAD_SERVICE`.
3382 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3384 // Parse `downloadUrl`.
3385 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3387 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3388 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3389 if (firstPartyCookiesEnabled) {
3390 // Get the cookies for `downloadUrl`.
3391 String cookies = cookieManager.getCookie(downloadUrl);
3393 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3394 downloadRequest.addRequestHeader("Cookie", cookies);
3397 // Get the file name from `dialogFragment`.
3398 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3399 String fileName = downloadFileNameEditText.getText().toString();
3401 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
3402 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
3403 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
3404 } else { // Only set the title using `fileName`.
3405 downloadRequest.setTitle(fileName);
3408 // Allow `MediaScanner` to index the download if it is a media file.
3409 downloadRequest.allowScanningByMediaScanner();
3411 // Add the URL as the description for the download.
3412 downloadRequest.setDescription(downloadUrl);
3414 // Show the download notification after the download is completed.
3415 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3417 // Remove the lint warning below that `downloadManager` might be `null`.
3418 assert downloadManager != null;
3420 // Initiate the download.
3421 downloadManager.enqueue(downloadRequest);
3422 } else { // The download is not an HTTP or HTTPS URI.
3423 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3428 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3429 // Get handles for the views from `dialogFragment`.
3430 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3431 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3432 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3434 // Store the bookmark strings.
3435 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3436 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3438 // Update the bookmark.
3439 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3440 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3441 } else { // Update the bookmark using the `WebView` favorite icon.
3442 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3443 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3444 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3445 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3447 // Update the bookmark and the favorite icon.
3448 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3451 // Update `bookmarksCursor` with the current contents of this folder.
3452 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3454 // Update the `ListView`.
3455 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3459 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3460 // Get handles for the views from `dialogFragment`.
3461 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3462 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3463 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3464 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3466 // Get the new folder name.
3467 String newFolderNameString = editFolderNameEditText.getText().toString();
3469 // Check if the favorite icon has changed.
3470 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3471 // Update the name in the database.
3472 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3473 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3474 // Get the new folder icon `Bitmap`.
3475 Bitmap folderIconBitmap;
3476 if (defaultFolderIconRadioButton.isChecked()) {
3477 // Get the default folder icon and convert it to a `Bitmap`.
3478 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3479 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3480 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3481 } else { // Use the `WebView` favorite icon.
3482 folderIconBitmap = favoriteIconBitmap;
3485 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3486 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3487 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3488 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3490 // Update the folder icon in the database.
3491 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3492 } else { // The folder icon and the name have changed.
3493 // Get the new folder icon `Bitmap`.
3494 Bitmap folderIconBitmap;
3495 if (defaultFolderIconRadioButton.isChecked()) {
3496 // Get the default folder icon and convert it to a `Bitmap`.
3497 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3498 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3499 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3500 } else { // Use the `WebView` favorite icon.
3501 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3504 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3505 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3506 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3507 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3509 // Update the folder name and icon in the database.
3510 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3513 // Update `bookmarksCursor` with the current contents of this folder.
3514 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3516 // Update the `ListView`.
3517 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3521 public void onHttpAuthenticationCancel() {
3522 // Cancel the `HttpAuthHandler`.
3523 httpAuthHandler.cancel();
3527 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3528 // Get handles for the `EditTexts`.
3529 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3530 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3532 // Proceed with the HTTP authentication.
3533 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3536 public void viewSslCertificate(View view) {
3537 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3538 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3539 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3543 public void onSslErrorCancel() {
3544 sslErrorHandler.cancel();
3548 public void onSslErrorProceed() {
3549 sslErrorHandler.proceed();
3553 public void onSslMismatchBack() {
3554 if (mainWebView.canGoBack()) { // There is a back page in the history.
3555 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3556 navigatingHistory = true;
3559 mainWebView.goBack();
3560 } else { // There are no pages to go back to.
3561 // Load a blank page
3567 public void onSslMismatchProceed() {
3568 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3569 ignorePinnedSslCertificate = true;
3573 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3574 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3575 navigatingHistory = true;
3577 // Load the history entry.
3578 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3582 public void onClearHistory() {
3583 // Clear the history.
3584 mainWebView.clearHistory();
3587 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3589 public void onBackPressed() {
3590 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3591 // Close the navigation drawer.
3592 drawerLayout.closeDrawer(GravityCompat.START);
3593 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3594 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3595 // close the bookmarks drawer.
3596 drawerLayout.closeDrawer(GravityCompat.END);
3597 } else { // A subfolder is displayed.
3598 // Place the former parent folder in `currentFolder`.
3599 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3601 // Load the new folder.
3602 loadBookmarksFolder();
3605 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3606 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3607 navigatingHistory = true;
3610 mainWebView.goBack();
3611 } else { // There isn't anything to do in Privacy Browser.
3612 // Pass `onBackPressed()` to the system.
3613 super.onBackPressed();
3617 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3618 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3619 String unformattedUrlString = urlTextBox.getText().toString().trim();
3621 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3622 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3623 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3624 if (!unformattedUrlString.startsWith("http")) {
3625 unformattedUrlString = "http://" + unformattedUrlString;
3628 // Initialize `unformattedUrl`.
3629 URL unformattedUrl = null;
3631 // 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.
3633 unformattedUrl = new URL(unformattedUrlString);
3634 } catch (MalformedURLException e) {
3635 e.printStackTrace();
3638 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3639 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3640 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3641 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3642 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3643 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3646 Uri.Builder formattedUri = new Uri.Builder();
3647 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3649 // Decode `formattedUri` as a `String` in `UTF-8`.
3650 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3652 // Sanitize the search input and convert it to a search.
3653 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3655 // Add the base search URL.
3656 formattedUrlString = searchURL + encodedUrlString;
3659 loadUrl(formattedUrlString);
3663 private void loadUrl(String url) {
3664 // Apply any custom domain settings.
3665 applyDomainSettings(url);
3668 mainWebView.loadUrl(url, customHeaders);
3670 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3671 urlIsLoading = true;
3674 public void findPreviousOnPage(View view) {
3675 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3676 mainWebView.findNext(false);
3679 public void findNextOnPage(View view) {
3680 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3681 mainWebView.findNext(true);
3684 public void closeFindOnPage(View view) {
3685 // Delete the contents of `find_on_page_edittext`.
3686 findOnPageEditText.setText(null);
3688 // Clear the highlighted phrases.
3689 mainWebView.clearMatches();
3691 // Hide the Find on Page `RelativeLayout`.
3692 findOnPageLinearLayout.setVisibility(View.GONE);
3694 // Show the URL app bar.
3695 supportAppBar.setVisibility(View.VISIBLE);
3697 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3698 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3701 private void applyAppSettings() {
3702 // Get a handle for the shared preferences.
3703 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3705 // Store the values from the shared preferences in variables.
3706 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3707 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3708 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3709 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3710 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3711 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3712 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
3713 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3714 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3715 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3716 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3717 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3718 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3719 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
3720 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3722 // Set the homepage, search, and proxy options.
3723 if (proxyThroughOrbot) { // Set the Tor options.
3724 // Set `torHomepageString` as `homepage`.
3725 homepage = torHomepageString;
3727 // If formattedUrlString is null assign the homepage to it.
3728 if (formattedUrlString == null) {
3729 formattedUrlString = homepage;
3732 // Set the search URL.
3733 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3734 searchURL = torSearchCustomURLString;
3735 } else { // Use the string from the pre-built list.
3736 searchURL = torSearchString;
3739 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3740 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3742 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3744 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3746 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3749 // Display a message to the user if we are waiting on Orbot.
3750 if (!orbotStatus.equals("ON")) {
3751 // Set `waitingForOrbot`.
3752 waitingForOrbot = true;
3754 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3755 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3757 } else { // Set the non-Tor options.
3758 // Set `homepageString` as `homepage`.
3759 homepage = homepageString;
3761 // If formattedUrlString is null assign the homepage to it.
3762 if (formattedUrlString == null) {
3763 formattedUrlString = homepage;
3766 // Set the search URL.
3767 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3768 searchURL = searchCustomURLString;
3769 } else { // Use the string from the pre-built list.
3770 searchURL = searchString;
3773 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3774 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3776 // Set the default `appBar` background. `this` refers to the context.
3778 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3780 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3783 // Reset `waitingForOrbot.
3784 waitingForOrbot = false;
3787 // Set swipe to refresh.
3788 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
3790 // Set Do Not Track status.
3791 if (doNotTrackEnabled) {
3792 customHeaders.put("DNT", "1");
3794 customHeaders.remove("DNT");
3797 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3798 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3799 if (hideSystemBarsOnFullscreen) { // Hide everything.
3800 // Remove the translucent navigation setting if it is currently flagged.
3801 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3803 // Remove the translucent status bar overlay.
3804 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3806 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3807 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3809 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3810 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3811 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
3813 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3814 } else { // Hide everything except the status and navigation bars.
3815 // Add the translucent status flag if it is unset.
3816 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3818 if (translucentNavigationBarOnFullscreen) {
3819 // Set the navigation bar to be translucent.
3820 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3822 // Set the navigation bar to be black.
3823 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3826 } else { // Switch to normal viewing mode.
3827 // Reset `inFullScreenBrowsingMode` to `false`.
3828 inFullScreenBrowsingMode = false;
3830 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3831 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3835 // Show the `BannerAd` in the free flavor.
3836 if (BuildConfig.FLAVOR.contentEquals("free")) {
3837 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
3838 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
3840 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3841 adView = findViewById(R.id.adview);
3844 // Remove the translucent navigation bar flag if it is set.
3845 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3847 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3848 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3850 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3851 rootCoordinatorLayout.setSystemUiVisibility(0);
3853 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3854 rootCoordinatorLayout.setFitsSystemWindows(true);
3858 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3859 @SuppressWarnings("deprecation")
3860 private void applyDomainSettings(String url) {
3861 // Reset `navigatingHistory`.
3862 navigatingHistory = false;
3864 // Parse the URL into a URI.
3865 Uri uri = Uri.parse(url);
3867 // Extract the domain from `uri`.
3868 String hostName = uri.getHost();
3870 // Initialize `loadingNewDomainName`.
3871 boolean loadingNewDomainName;
3873 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3874 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3875 //noinspection SimplifiableIfStatement
3876 if ((hostName == null) || (currentDomainName == null)) {
3877 loadingNewDomainName = true;
3878 } else { // Determine if `hostName` equals `currentDomainName`.
3879 loadingNewDomainName = !hostName.equals(currentDomainName);
3882 // 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.
3883 if (loadingNewDomainName) {
3884 // Set the new `hostname` as the `currentDomainName`.
3885 currentDomainName = hostName;
3887 // Reset `ignorePinnedSslCertificate`.
3888 ignorePinnedSslCertificate = false;
3890 // Reset `favoriteIconBitmap` and display it in the `appbar`.
3891 favoriteIconBitmap = favoriteIconDefaultBitmap;
3892 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3894 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3895 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3896 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3898 // Get a full cursor from `domainsDatabaseHelper`.
3899 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3901 // Initialize `domainSettingsSet`.
3902 Set<String> domainSettingsSet = new HashSet<>();
3904 // Get the domain name column index.
3905 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3907 // Populate `domainSettingsSet`.
3908 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3909 // Move `domainsCursor` to the current row.
3910 domainNameCursor.moveToPosition(i);
3912 // Store the domain name in `domainSettingsSet`.
3913 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3916 // Close `domainNameCursor.
3917 domainNameCursor.close();
3919 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3920 domainSettingsApplied = false;
3921 String domainNameInDatabase = null;
3923 // Check the hostname.
3924 if (domainSettingsSet.contains(hostName)) {
3925 domainSettingsApplied = true;
3926 domainNameInDatabase = hostName;
3929 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3930 if (hostName != null) {
3931 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3932 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3933 domainSettingsApplied = true;
3934 domainNameInDatabase = "*." + hostName;
3937 // Strip out the lowest subdomain of `host`.
3938 hostName = hostName.substring(hostName.indexOf(".") + 1);
3942 // Get a handle for the shared preference. `this` references the current context.
3943 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3945 // Store the general preference information.
3946 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3947 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3948 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3949 nightMode = sharedPreferences.getBoolean("night_mode", false);
3951 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3952 // Get a cursor for the current host and move it to the first position.
3953 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3954 currentHostDomainSettingsCursor.moveToFirst();
3956 // Get the settings from the cursor.
3957 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3958 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3959 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3960 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3961 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3962 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3963 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3964 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3965 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3966 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3967 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3968 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3969 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3970 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3971 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3972 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3973 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3975 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3976 switch (nightModeInt) {
3977 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3981 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3986 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3988 javaScriptEnabled = true;
3991 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3992 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3993 pinnedDomainSslStartDate = null;
3995 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3998 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3999 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
4000 pinnedDomainSslEndDate = null;
4002 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
4005 // Close `currentHostDomainSettingsCursor`.
4006 currentHostDomainSettingsCursor.close();
4008 // Apply the domain settings.
4009 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4010 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4011 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4012 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4014 // Apply the font size.
4015 if (fontSize == 0) { // Apply the default font size.
4016 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4017 } else { // Apply the specified font size.
4018 mainWebView.getSettings().setTextZoom(fontSize);
4021 // Set third-party cookies status if API >= 21.
4022 if (Build.VERSION.SDK_INT >= 21) {
4023 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4026 // 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.
4027 // <https://redmine.stoutner.com/issues/160>
4028 if (!urlIsLoading) {
4029 switch (userAgentString) {
4030 case "System default user agent":
4031 // Set the user agent according to the system default.
4032 switch (defaultUserAgentString) {
4033 case "WebView default user agent":
4034 // Set the user agent to `""`, which uses the default value.
4035 mainWebView.getSettings().setUserAgentString("");
4038 case "Custom user agent":
4039 // Set the custom user agent.
4040 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4044 // Use the selected user agent.
4045 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
4049 case "WebView default user agent":
4050 // Set the user agent to `""`, which uses the default value.
4051 mainWebView.getSettings().setUserAgentString("");
4055 // Use the selected user agent.
4056 mainWebView.getSettings().setUserAgentString(userAgentString);
4059 // Store the applied user agent string.
4060 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4063 // 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.
4065 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4067 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4069 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
4070 // Store the values from `sharedPreferences` in variables.
4071 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
4072 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
4073 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
4074 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
4075 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
4077 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4079 javaScriptEnabled = true;
4082 // Apply the default settings.
4083 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4084 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4085 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4086 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4087 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4089 // Reset the pinned SSL certificate information.
4090 domainSettingsDatabaseId = -1;
4091 pinnedDomainSslCertificate = false;
4092 pinnedDomainSslIssuedToCNameString = "";
4093 pinnedDomainSslIssuedToONameString = "";
4094 pinnedDomainSslIssuedToUNameString = "";
4095 pinnedDomainSslIssuedByCNameString = "";
4096 pinnedDomainSslIssuedByONameString = "";
4097 pinnedDomainSslIssuedByUNameString = "";
4098 pinnedDomainSslStartDate = null;
4099 pinnedDomainSslEndDate = null;
4101 // Set third-party cookies status if API >= 21.
4102 if (Build.VERSION.SDK_INT >= 21) {
4103 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4106 // 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.
4107 // <https://redmine.stoutner.com/issues/160>
4108 if (!urlIsLoading) {
4109 switch (defaultUserAgentString) {
4110 case "WebView default user agent":
4111 // Set the user agent to `""`, which uses the default value.
4112 mainWebView.getSettings().setUserAgentString("");
4115 case "Custom user agent":
4116 // Set the custom user agent.
4117 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4121 // Use the selected user agent.
4122 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
4125 // Store the applied user agent string.
4126 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4129 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4130 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4133 // Close `domainsDatabaseHelper`.
4134 domainsDatabaseHelper.close();
4136 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
4137 onTheFlyDisplayImagesSet = false;
4138 setDisplayWebpageImages();
4140 // Update the privacy icons, but only if `mainMenu` has already been populated.
4141 if (mainMenu != null) {
4142 updatePrivacyIcons(true);
4147 private void setDisplayWebpageImages() {
4148 if (!onTheFlyDisplayImagesSet) {
4149 if (domainSettingsApplied) { // Custom domain settings are applied.
4150 switch (displayWebpageImagesInt) {
4151 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4152 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4155 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4156 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4159 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4160 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4163 } else { // Default settings are applied.
4164 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4169 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4170 // Get handles for the icons.
4171 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4172 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4173 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4174 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
4176 // Update `privacyIcon`.
4177 if (javaScriptEnabled) { // JavaScript is enabled.
4178 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
4179 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4180 privacyIconMenuItem.setIcon(R.drawable.warning);
4181 } else { // All the dangerous features are disabled.
4182 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
4185 // Update `firstPartyCookiesIcon`.
4186 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4187 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
4188 } else { // First-party cookies are disabled.
4190 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4192 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
4196 // Update `domStorageIcon`.
4197 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4198 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
4199 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4201 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4203 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4205 } else { // JavaScript is disabled, so DOM storage is ghosted.
4207 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4209 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4213 // Update `formDataIcon`.
4214 if (saveFormDataEnabled) { // Form data is enabled.
4215 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
4216 } else { // Form data is disabled.
4218 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
4220 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
4224 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4225 if (runInvalidateOptionsMenu) {
4226 invalidateOptionsMenu();
4230 private void highlightUrlText() {
4231 String urlString = urlTextBox.getText().toString();
4233 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4234 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4235 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4236 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4239 // Get the index of the `/` immediately after the domain name.
4240 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4242 // De-emphasize the text after the domain name.
4243 if (endOfDomainName > 0) {
4244 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4248 private void loadBookmarksFolder() {
4249 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
4250 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4252 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4253 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4255 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4256 // Inflate the individual item layout. `false` does not attach it to the root.
4257 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4261 public void bindView(View view, Context context, Cursor cursor) {
4262 // Get handles for the views.
4263 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4264 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4266 // Get the favorite icon byte array from the `Cursor`.
4267 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4269 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4270 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4272 // Display the bitmap in `bookmarkFavoriteIcon`.
4273 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4275 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4276 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4277 bookmarkNameTextView.setText(bookmarkNameString);
4279 // Make the font bold for folders.
4280 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4281 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4282 } else { // Reset the font to default for normal bookmarks.
4283 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4288 // Populate the `ListView` with the adapter.
4289 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4291 // Set the bookmarks drawer title.
4292 if (currentBookmarksFolder.isEmpty()) {
4293 bookmarksTitleTextView.setText(R.string.bookmarks);
4295 bookmarksTitleTextView.setText(currentBookmarksFolder);