2 * Copyright © 2015-2018 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.annotation.SuppressLint;
25 import android.app.DialogFragment;
26 import android.app.DownloadManager;
27 import android.content.BroadcastReceiver;
28 import android.content.ClipData;
29 import android.content.ClipboardManager;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.SharedPreferences;
34 import android.content.res.Configuration;
35 import android.database.Cursor;
36 import android.graphics.Bitmap;
37 import android.graphics.BitmapFactory;
38 import android.graphics.Typeface;
39 import android.graphics.drawable.BitmapDrawable;
40 import android.graphics.drawable.Drawable;
41 import android.net.Uri;
42 import android.net.http.SslCertificate;
43 import android.net.http.SslError;
44 import android.os.Build;
45 import android.os.Bundle;
46 import android.os.Handler;
47 import android.preference.PreferenceManager;
48 import android.print.PrintDocumentAdapter;
49 import android.print.PrintManager;
50 import android.support.annotation.NonNull;
51 import android.support.design.widget.CoordinatorLayout;
52 import android.support.design.widget.FloatingActionButton;
53 import android.support.design.widget.NavigationView;
54 import android.support.design.widget.Snackbar;
55 import android.support.v4.content.ContextCompat;
56 // `ShortcutInfoCompat`, `ShortcutManagerCompat`, and `IconCompat` can be switched to the non-compat version once API >= 26.
57 import android.support.v4.content.pm.ShortcutInfoCompat;
58 import android.support.v4.content.pm.ShortcutManagerCompat;
59 import android.support.v4.graphics.drawable.IconCompat;
60 import android.support.v4.view.GravityCompat;
61 import android.support.v4.widget.DrawerLayout;
62 import android.support.v4.widget.SwipeRefreshLayout;
63 import android.support.v7.app.ActionBar;
64 import android.support.v7.app.ActionBarDrawerToggle;
65 import android.support.v7.app.AppCompatActivity;
66 import android.support.v7.app.AppCompatDialogFragment;
67 import android.support.v7.widget.Toolbar;
68 import android.text.Editable;
69 import android.text.Spanned;
70 import android.text.TextWatcher;
71 import android.text.style.ForegroundColorSpan;
72 import android.util.Log;
73 import android.util.Patterns;
74 import android.view.ContextMenu;
75 import android.view.GestureDetector;
76 import android.view.KeyEvent;
77 import android.view.Menu;
78 import android.view.MenuItem;
79 import android.view.MotionEvent;
80 import android.view.View;
81 import android.view.ViewGroup;
82 import android.view.WindowManager;
83 import android.view.inputmethod.InputMethodManager;
84 import android.webkit.CookieManager;
85 import android.webkit.HttpAuthHandler;
86 import android.webkit.SslErrorHandler;
87 import android.webkit.WebBackForwardList;
88 import android.webkit.WebChromeClient;
89 import android.webkit.WebResourceResponse;
90 import android.webkit.WebStorage;
91 import android.webkit.WebView;
92 import android.webkit.WebViewClient;
93 import android.webkit.WebViewDatabase;
94 import android.widget.CursorAdapter;
95 import android.widget.EditText;
96 import android.widget.FrameLayout;
97 import android.widget.ImageView;
98 import android.widget.LinearLayout;
99 import android.widget.ListView;
100 import android.widget.ProgressBar;
101 import android.widget.RadioButton;
102 import android.widget.RelativeLayout;
103 import android.widget.TextView;
105 import com.stoutner.privacybrowser.BannerAd;
106 import com.stoutner.privacybrowser.BuildConfig;
107 import com.stoutner.privacybrowser.R;
108 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
109 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
110 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
111 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
112 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
113 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
114 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
115 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
116 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
117 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
118 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
119 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
120 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
121 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
122 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
123 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
125 import java.io.BufferedReader;
126 import java.io.ByteArrayInputStream;
127 import java.io.ByteArrayOutputStream;
129 import java.io.IOException;
130 import java.io.InputStreamReader;
131 import java.io.UnsupportedEncodingException;
132 import java.net.MalformedURLException;
134 import java.net.URLDecoder;
135 import java.net.URLEncoder;
136 import java.util.Date;
137 import java.util.HashMap;
138 import java.util.HashSet;
139 import java.util.LinkedList;
140 import java.util.List;
141 import java.util.Map;
142 import java.util.Set;
143 import java.util.regex.Pattern;
145 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
146 public class MainWebViewActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener, CreateBookmarkDialog.CreateBookmarkListener,
147 CreateBookmarkFolderDialog.CreateBookmarkFolderListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener, DownloadFileDialog.DownloadFileListener,
148 DownloadImageDialog.DownloadImageListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener,
149 NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener,
150 UrlHistoryDialog.UrlHistoryListener {
152 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`,
153 // `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
154 // `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`,
155 // and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
156 public static boolean darkTheme;
158 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
159 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
160 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
161 public static Bitmap favoriteIconBitmap;
163 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
164 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
165 public static String formattedUrlString;
167 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
168 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
169 public static SslCertificate sslCertificate;
171 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
172 public static String orbotStatus;
174 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
175 public static String webViewTitle;
177 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
178 public static String appliedUserAgentString;
180 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
181 public static boolean displayWebpageImagesBoolean;
183 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
184 public static boolean reloadOnRestart;
186 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
187 public static boolean loadUrlOnRestart;
189 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
190 public static boolean restartFromBookmarksActivity;
192 // `easyListVersion` is public static so it can be accessed from `AboutTabFragment`. It is also used in `onCreate()`.
193 public static String easyListVersion;
195 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
196 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
197 public static String currentBookmarksFolder;
199 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
200 public static int domainSettingsDatabaseId;
202 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
203 public static String pinnedDomainSslIssuedToCNameString;
204 public static String pinnedDomainSslIssuedToONameString;
205 public static String pinnedDomainSslIssuedToUNameString;
206 public static String pinnedDomainSslIssuedByCNameString;
207 public static String pinnedDomainSslIssuedByONameString;
208 public static String pinnedDomainSslIssuedByUNameString;
209 public static Date pinnedDomainSslStartDate;
210 public static Date pinnedDomainSslEndDate;
213 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
214 private ActionBar appBar;
216 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
217 private boolean navigatingHistory;
219 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
220 private Bitmap favoriteIconDefaultBitmap;
222 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
223 private DrawerLayout drawerLayout;
225 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
226 private CoordinatorLayout rootCoordinatorLayout;
228 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
229 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
230 private WebView mainWebView;
232 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
233 private FrameLayout fullScreenVideoFrameLayout;
235 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
236 private SwipeRefreshLayout swipeRefreshLayout;
238 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
239 private RelativeLayout urlAppBarRelativeLayout;
241 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
242 private ImageView favoriteIconImageView;
244 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
245 private CookieManager cookieManager;
247 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
248 private final Map<String, String> customHeaders = new HashMap<>();
250 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
251 private boolean javaScriptEnabled;
253 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
254 private boolean firstPartyCookiesEnabled;
256 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
257 private boolean thirdPartyCookiesEnabled;
259 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
260 private boolean domStorageEnabled;
262 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
263 private boolean saveFormDataEnabled;
265 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
266 private boolean nightMode;
268 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
269 private boolean swipeToRefreshEnabled;
271 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
272 private String homepage;
274 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
275 private String searchURL;
277 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
278 private boolean adBlockerEnabled;
280 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
281 private Runtime privacyBrowserRuntime;
283 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
284 private boolean incognitoModeEnabled;
286 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
287 private boolean fullScreenBrowsingModeEnabled;
289 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
290 private boolean inFullScreenBrowsingMode;
292 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
293 private boolean hideSystemBarsOnFullscreen;
295 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
296 private boolean translucentNavigationBarOnFullscreen;
298 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
299 private boolean reapplyDomainSettingsOnRestart;
301 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
302 private String currentDomainName;
304 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
305 private boolean ignorePinnedSslCertificate;
307 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
308 private boolean waitingForOrbot;
310 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
311 private boolean domainSettingsApplied;
313 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
314 private int displayWebpageImagesInt;
316 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
317 private boolean onTheFlyDisplayImagesSet;
319 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
320 private String waitingForOrbotHTMLString;
322 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
323 private String privateDataDirectoryString;
325 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
326 private LinearLayout findOnPageLinearLayout;
328 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
329 private EditText findOnPageEditText;
331 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
332 private Menu mainMenu;
334 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
335 private ActionBarDrawerToggle drawerToggle;
337 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
338 private Toolbar supportAppBar;
340 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
341 private EditText urlTextBox;
343 // The color spans are used in `onCreate()` and `highlightUrlText()`.
344 private ForegroundColorSpan redColorSpan;
345 private ForegroundColorSpan initialGrayColorSpan;
346 private ForegroundColorSpan finalGrayColorSpan;
348 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
351 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
352 private SslErrorHandler sslErrorHandler;
354 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
355 private static HttpAuthHandler httpAuthHandler;
357 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
358 private InputMethodManager inputMethodManager;
360 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
361 private RelativeLayout mainWebViewRelativeLayout;
363 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
364 private boolean urlIsLoading;
366 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
367 private boolean pinnedDomainSslCertificate;
369 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
370 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
372 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
373 private ListView bookmarksListView;
375 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
376 private TextView bookmarksTitleTextView;
378 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
379 private Cursor bookmarksCursor;
381 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
382 private CursorAdapter bookmarksCursorAdapter;
384 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
385 private String oldFolderNameString;
388 // 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.
389 @SuppressLint({"SetJavaScriptEnabled"})
390 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
391 @SuppressWarnings("deprecation")
392 protected void onCreate(Bundle savedInstanceState) {
393 // Get a handle for `sharedPreferences`. `this` references the current context.
394 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
396 // Get the theme preference.
397 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
399 // Set the activity theme.
401 setTheme(R.style.PrivacyBrowserDark);
403 setTheme(R.style.PrivacyBrowserLight);
406 // Run the default commands.
407 super.onCreate(savedInstanceState);
409 Log.i("BlockLists", "Begin populating block lists.");
411 // Initialize the block lists.
412 List<String> mainWhiteList = new LinkedList<>();
413 List<String[]> multiEntryWhiteList = new LinkedList<>();
414 List<String[]> domainWhiteList = new LinkedList<>();
415 List<String[]> thirdPartyDomainWhiteList = new LinkedList<>();
416 List<String> mainBlockList = new LinkedList<>();
417 List<String> initialBlockList = new LinkedList<>();
418 List<String> finalBlockList = new LinkedList<>();
419 List<String> thirdPartyBlockList = new LinkedList<>();
420 List<String> thirdPartyInitialBlockList = new LinkedList<>();
421 List<String[]> multiEntryBlockList = new LinkedList<>();
422 List<String[]> multiEntryInitialBlockList = new LinkedList<>();
423 List<String[]> multiEntryFinalBlockList = new LinkedList<>();
424 List<String[]> domainBlockList = new LinkedList<>();
425 List<String[]> domainInitialBlockList = new LinkedList<>();
426 List<String[]> domainFinalBlockList = new LinkedList<>();
427 List<String[]> domainRegularExpressionBlockList = new LinkedList<>();
428 List<String[]> thirdPartyMultiEntryBlockList = new LinkedList<>();
429 List<String[]> thirdPartyMultiEntryInitialBlockList = new LinkedList<>();
430 List<String[]> thirdPartyDomainBlockList = new LinkedList<>();
431 List<String> regularExpressionBlockList = new LinkedList<>();
432 List<String> thirdPartyRegularExpressionBlockList = new LinkedList<>();
434 // Populate the block lists.
436 // Load `easylist.txt` into a `BufferedReader`.
437 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("easylist.txt")));
439 // Create a string for storing the block list entries.
440 String blockListEntry;
443 while ((blockListEntry = bufferedReader.readLine()) != null) {
444 // Remove any `^` from the block list entry. Privacy Browser does not process them in the interest of efficiency.
445 blockListEntry = blockListEntry.replace("^", "");
447 //noinspection StatementWithEmptyBody
448 if (blockListEntry.contains("##") || blockListEntry.contains("#?#") || blockListEntry.contains("#@#") || blockListEntry.startsWith("[")) {
449 // Entries that contain `##`, `#?#`, and `#@#` are for hiding elements in the main page's HTML. Entries that start with `[` describe the AdBlock compatibility level.
451 // Do nothing. Privacy Browser does not currently use these entries.
453 //Log.i("BlackLists", "Not added: " + adBlockerEntry);
454 } else if (blockListEntry.startsWith("!")){ // Entries that begin with `!` are comments.
455 if (blockListEntry.startsWith("! Version:")) {
456 // Store the EasyList version number.
457 easyListVersion = blockListEntry.substring(11);
460 //Log.i("BlackLists", "Not added: " + adBlockerEntry);
461 } else if (blockListEntry.startsWith("@@")) { // Entries that begin with `@@` are whitelists.
463 blockListEntry = blockListEntry.substring(2);
465 // Strip out an initial `||` Privacy Browser doesn't differentiate against items that only match against the end of the domain name.
466 if (blockListEntry.startsWith("||")) {
467 blockListEntry = blockListEntry.substring(2);
472 // mainWhiteList.add(blockListEntry);
474 // Log.i("BlockLists", "Main white list added: " + blockListEntry);
475 } else if (blockListEntry.endsWith("|")){ // Entries that end with `|` match against the end of the URL.
476 // Strip out the final "|"
477 blockListEntry = blockListEntry.substring(0, blockListEntry.length() - 1);
479 // Strip out any initial `||`. They are redundant in this case because the block list entry is being matched against the end of the URL.
480 if (blockListEntry.startsWith("||")) {
481 blockListEntry = blockListEntry.substring(2);
484 if (blockListEntry.contains("*")) { // Process a double final entry.
485 int wildcardIndex = blockListEntry.indexOf("*");
487 String firstEntry = blockListEntry.substring(0, wildcardIndex);
488 String secondEntry = blockListEntry.substring(wildcardIndex + 1);
491 String[] doubleEntry = {firstEntry, secondEntry};
493 multiEntryFinalBlockList.add(doubleEntry);
495 //Log.i("BlockLists", "Multi entry final block list added: " + firstEntry + " , " + secondEntry).
496 } else { // Process a standard final entry.
497 finalBlockList.add(blockListEntry);
499 //Log.i("BlockLists", "Final block list added: " + blockListEntry);
501 } else if (blockListEntry.contains("$")) { // Entries that contain `$` use filter options.
502 // Strip out any initial `||`. These will be treated like any other entry.
503 if (blockListEntry.startsWith("||")) {
504 blockListEntry = blockListEntry.substring(2);
507 if (blockListEntry.contains("third-party")) { // Process third party blocklist entries.
508 //noinspection StatementWithEmptyBody
509 if (blockListEntry.contains("~third-party")) { // Process third-party white list entries.
510 // Do not process these white list entries. They are designed to combine with block filters that Privacy Browser doesn't use, like `subdocument` and `xmlhttprequest`.
512 // Log.i("BlockLists", "Not added: " + blockListEntry);
513 } else if (blockListEntry.contains("domain=")) { // Process third-party domain block list entries.
514 if (blockListEntry.startsWith("|")) { // Third-party domain initial block list entries.
516 } else if (blockListEntry.contains("\\")) { // Third-party domain regular expressions.
518 } else { // Third-party domain entries.
520 String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
521 String filters = blockListEntry.substring(blockListEntry.indexOf("$") + 1);
522 String domains = filters.substring(filters.indexOf("domain=") + 7);
524 // Strip any trailing "*" on the entries.
525 if (entry.endsWith("*")) {
526 entry = entry.substring(0, entry.length() - 1);
529 if (entry.contains("*")) { // Third-party domain multi-entry.
531 } else { // Third-party domain single entry.
533 boolean whiteListDomain = false;
535 // Process each domain.
539 if (domains.contains("|")) {
540 // Get the first domain
541 domain = domains.substring(0, domains.indexOf("|"));
543 // Remove the first domain from the list.
544 domains = domains.substring(domains.indexOf("|") + 1);
549 // Differentiate between block list domains and white list domains.
550 if (domain.startsWith("~")) { // White list third-party domain entry.
551 // Strip the initial `~`.
552 domain = domain.substring(1);
554 // Set the white list domain flag and store the domain.
555 whiteListDomain = true;
557 // Create the domain entry.
558 String[] domainEntry = {domain, entry};
560 // Add the entry to the third-party domain white list.
561 thirdPartyDomainWhiteList.add(domainEntry);
563 Log.i("BlockLists", "Third-party domain white list added: " + domain + " , " + entry);
564 } else { // Block list third-party domain entry.
565 String[] domainEntry = {domain, entry};
567 thirdPartyDomainBlockList.add(domainEntry);
569 // Log.i("BlockLists", "Third-party domain block list added: " + domain + " , " + entry);
571 } while (domains.contains("|"));
573 // Add a third-party block list entry if a white list domain was processed.
574 if (whiteListDomain) {
575 // Add an entry to the third-party block list.
576 thirdPartyBlockList.add(entry);
578 Log.i("BlockLists", "Third-party block list added: " + entry);
582 } else if (blockListEntry.startsWith("|")) { // Third-party initial block list entries.
583 // Strip the initial `|`.
584 blockListEntry = blockListEntry.substring(1);
587 String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
589 if (entry.contains("*")) { // Process a third-party multi-entry initial block list.
590 int wildcardIndex = entry.indexOf("*");
592 String firstEntry = entry.substring(0, wildcardIndex);
593 String secondEntry = entry.substring(wildcardIndex + 1);
595 String[] thirdPartyDoubleEntry = {firstEntry, secondEntry};
597 thirdPartyMultiEntryInitialBlockList.add(thirdPartyDoubleEntry);
599 //Log.i("BlockLists", "Third-party multi-entry initial block list added: " + firstEntry + " , " + secondEntry);
601 thirdPartyInitialBlockList.add(entry);
603 //Log.i("BlockLists", "Third-party initial block list added: " + entry);
605 } else if (blockListEntry.contains("*")) { // Process third-party multi-entry or regular expression blocklist entries.
607 String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
609 if (entry.endsWith("*")) {
610 // Strip the final `*`.
611 entry = entry.substring(0, entry.length() - 1);
613 // Add the entry to the block list.
614 thirdPartyBlockList.add(entry);
616 //Log.i("BlockLists", "Third party block list added: " + entry);
617 } else if (entry.contains("\\")) { // Process a third-party regular expression.
618 // Add the entry to the third-party regular expression block list.
619 thirdPartyRegularExpressionBlockList.add(entry);
621 //Log.i("BlockLists", "Third-party regular expression block list added: " + entry);
622 } else { // There are two or more entries.
623 int wildcardIndex = entry.indexOf("*");
625 String firstEntry = entry.substring(0, wildcardIndex);
626 String secondEntry = entry.substring(wildcardIndex + 1);
628 if (secondEntry.contains("*")) { // there are three or more entries.
629 int secondWildcardIndex = secondEntry.indexOf("*");
631 String realSecondEntry = secondEntry.substring(0, secondWildcardIndex);
632 String thirdEntry = secondEntry.substring(secondWildcardIndex + 1);
634 if (thirdEntry.contains("*")) { // Process a third-party quadruple entry.
635 int thirdWildcardIndex = thirdEntry.indexOf("*");
637 String realThirdEntry = thirdEntry.substring(0, thirdWildcardIndex);
638 String fourthEntry = thirdEntry.substring(thirdWildcardIndex + 1);
640 String[] thirdPartyQuadrupleEntry = {firstEntry, realSecondEntry, realThirdEntry, fourthEntry};
642 thirdPartyMultiEntryBlockList.add(thirdPartyQuadrupleEntry);
644 //Log.i("BlockLists", "Third-party multi-entry block list added: " + firstEntry + " , " + realSecondEntry + " , " + realThirdEntry + " , " + fourthEntry);
645 } else { // Process a third-party triple entry.
646 String[] thirdPartyTripleEntry = {firstEntry, realSecondEntry, thirdEntry};
648 thirdPartyMultiEntryBlockList.add(thirdPartyTripleEntry);
650 //Log.i("BlockLists", "Third-party multi-entry block list added: " + firstEntry + " , " + realSecondEntry + " , " + thirdEntry);
652 } else { // Process a third-party double entry.
653 String[] thirdPartyDoubleEntry = {firstEntry, secondEntry};
655 thirdPartyMultiEntryBlockList.add(thirdPartyDoubleEntry);
657 //Log.i("BlockLists", "Third-party multi-entry block list added: " + firstEntry + " , " + secondEntry);
660 } else { // Process standard third party entries.
662 String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
664 // Add the entry to the block list.
665 thirdPartyBlockList.add(entry);
667 //Log.i("BlockLists", "Third party block list added: " + entry);
669 } else if (blockListEntry.substring(blockListEntry.indexOf("$")).contains("domain")) {
670 if (blockListEntry.contains("~")) { // Whitelist.
671 // Separate the filters.
672 String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
673 String filters = blockListEntry.substring(blockListEntry.indexOf("$") + 1);
674 String domains = filters.substring(filters.indexOf("domain=") + 7);
676 // Strip any final `*` from the entry. They are redundant.
677 if (entry.endsWith("*")) {
678 entry = entry.substring(0, entry.length() - 1);
681 // Process each domain.
685 if (domains.contains("|")) {
686 // Get the first domain
687 domain = domains.substring(0, domains.indexOf("|"));
689 // Remove the first domain from the list.
690 domains = domains.substring(domains.indexOf("|") + 1);
695 // Strip the initial `~`.
696 domain = domain.substring(1);
698 if (entry.contains("*")) { // Process a double entry.
699 int wildcardIndex = entry.indexOf("*");
701 String firstEntry = entry.substring(0, wildcardIndex);
702 String secondEntry = entry.substring(wildcardIndex + 1);
704 String[] domainDoubleEntry = {firstEntry, secondEntry};
706 domainWhiteList.add(domainDoubleEntry);
708 //Log.i("BlockLists", "Domain white list added: " + domain + " , " + firstEntry + " , " + secondEntry);
709 } else { // Process a single entry.
710 String[] domainEntry = {domain, entry};
712 domainWhiteList.add(domainEntry);
714 //Log.i("BlockLists", "Domain white list added: " + domain + " , " + entry);
716 } while (domains.contains("|"));
717 } else { // The block list entry contains a domain, but not a third party designation and isn't a whitelist.
718 // Separate the filters.
719 String entry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
720 String filters = blockListEntry.substring(blockListEntry.indexOf("$") + 1);
721 String domains = filters.substring(filters.indexOf("domain=") + 7);
723 // Only process the block list item if the entry is not null. Some lines in EasyList begin with `$websocket`, which create a null entry.
724 if (!entry.equals("")) {
728 if (domains.contains("|")) {
729 // Get the first domain.
730 domain = domains.substring(0, domains.indexOf("|"));
732 // Remove the first domain from the list.
733 domains = domains.substring(domains.indexOf("|") + 1);
738 if (entry.contains("*")) {
739 int wildcardIndex = entry.indexOf("*");
741 String firstEntry = entry.substring(0, wildcardIndex);
742 String secondEntry = entry.substring(wildcardIndex + 1);
744 String[] domainDoubleEntry = {domain, firstEntry, secondEntry};
746 domainBlockList.add(domainDoubleEntry);
748 //Log.i("BlockLists", "Domain double entry block list added: " + domain + " , " + firstEntry + " , " + secondEntry);
749 } else if (entry.startsWith("|")) {
750 // Remove the initial `|`;
751 String entryBase = entry.substring(1);
753 //noinspection StatementWithEmptyBody
754 if (entryBase.equals("http://") || entryBase.equals("https://")) {
755 // Do nothing. These entries will entirely block the website.
756 // Often the original entry blocks `$script` but Privacy Browser does not currently differentiate between scripts and other entries.
758 String[] domainEntry = {domain, entryBase};
760 domainInitialBlockList.add(domainEntry);
762 //Log.i("BlockLists", "Domain initial block list added: " + domain + " , " + entryBase);
764 } else if (entry.endsWith("|")) {
765 // Remove the final `|`.
766 String entryBase = entry.substring(0, entry.length() - 1);
768 String[] domainEntry = {domain, entryBase};
770 domainFinalBlockList.add(domainEntry);
772 //Log.i("BlockLists", "Domain final block list added: " + domain + " , " + entryBase);
773 } else if (entry.contains("\\")) {
774 String[] domainEntry = {domain, entry};
776 domainRegularExpressionBlockList.add(domainEntry);
778 // Log.i("BlockLists", "Domain regular expression block list added: " + domain + " , " + entry);
780 String[] domainEntry = {domain, entry};
782 domainBlockList.add(domainEntry);
784 //Log.i("BlockLists", "Domain block list added: " + domain + " , " + entry);
786 } while (domains.contains("|"));
789 } else if (blockListEntry.contains("~")) { // Whitelist entries.
790 // Remove the filter options.
791 blockListEntry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
793 // Strip any trailing `*`.
794 if (blockListEntry.endsWith("*")) {
795 blockListEntry = blockListEntry.substring(0, blockListEntry.length() -1);
798 if (blockListEntry.contains("*")) {
799 int wildcardIndex = blockListEntry.indexOf("*");
801 String firstEntry = blockListEntry.substring(0, wildcardIndex);
802 String secondEntry = blockListEntry.substring(wildcardIndex + 1);
805 String[] doubleEntry = {firstEntry, secondEntry};
807 multiEntryWhiteList.add(doubleEntry);
809 //Log.i("BlockLists", "Multi entry white list added: " + firstEntry + " , " + secondEntry);
811 mainWhiteList.add(blockListEntry);
813 // Log.i("BlockLists", "Main white list added: " + blockListEntry);
815 } else if (blockListEntry.contains("\\")) { // Regular expressions.
816 // Remove the filter options.
817 blockListEntry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
819 regularExpressionBlockList.add(blockListEntry);
821 //Log.i("BlockLists", "Regular expression list added: " + blockListEntry);
823 // Remove the filter options.
824 blockListEntry = blockListEntry.substring(0, blockListEntry.indexOf("$"));
826 // Strip any trailing `*`. These are redundant.
827 if (blockListEntry.endsWith("*")) {
828 blockListEntry = blockListEntry.substring(0, blockListEntry.length() - 1);
831 if (blockListEntry.contains("*")) { // Use a multi entry list.
832 int wildcardIndex = blockListEntry.indexOf("*");
834 String firstEntry = blockListEntry.substring(0, wildcardIndex);
835 String secondEntry = blockListEntry.substring(wildcardIndex + 1);
837 // Remove `.*` if it appears at the beginning of the second entry.
838 if (secondEntry.startsWith(".*")) {
839 secondEntry = secondEntry.substring(2);
842 // Create a third entry if required.
843 if (secondEntry.contains("*")) {
844 wildcardIndex = secondEntry.indexOf("*");
846 String thirdEntry = secondEntry.substring(wildcardIndex + 1);
847 secondEntry = secondEntry.substring(0, wildcardIndex);
850 if (thirdEntry.endsWith("|")) {
851 thirdEntry = thirdEntry.substring(0, thirdEntry.length() - 1);
853 String[] tripleEntry = {firstEntry, secondEntry, thirdEntry};
855 multiEntryFinalBlockList.add(tripleEntry);
857 //Log.i("BlockLists", "Multi entry final tripple block list added: " + firstEntry + " , " + secondEntry + " , " + thirdEntry);
859 String[] tripleEntry = {firstEntry, secondEntry, thirdEntry};
861 multiEntryBlockList.add(tripleEntry);
863 // Log.i("BlockLists", "Multi entry tripple block list added: " + firstEntry + " , " + secondEntry + " , " + thirdEntry);
865 } else { // This is a double entry.
866 if (firstEntry.startsWith("|")) {
867 String[] doubleEntry = {firstEntry.substring(1), secondEntry};
869 multiEntryInitialBlockList.add(doubleEntry);
871 //Log.i("BlockLists", "Multi entry initial block list added: " + firstEntry.substring(1) + " , " + secondEntry);
873 String[] doubleEntry = {firstEntry, secondEntry};
875 multiEntryBlockList.add(doubleEntry);
877 //Log.i("BlockLists", "Multi entry block list added: " + firstEntry + " , " + secondEntry);
880 } else if (blockListEntry.startsWith("|")) { // Populate the initial block list.
881 // Strip the initial `|`.
882 blockListEntry = blockListEntry.substring(1);
884 // Populate the initial block list.
885 initialBlockList.add(blockListEntry);
887 //Log.i("BlockLists", "Initial block list added: " + blockListEntry);
888 } else { // Populate the main block list.
889 mainBlockList.add(blockListEntry);
891 //Log.i("BlockLists", "Main block list added: " + blockListEntry);
894 } else { // Populate the standard lists.
895 // Strip out any initial `||`. These will be treated like any other entry.
896 if (blockListEntry.startsWith("||")) {
897 blockListEntry = blockListEntry.substring(2);
900 // Strip out any initial `*`.
901 if (blockListEntry.startsWith("*")) {
902 blockListEntry = blockListEntry.substring(1);
905 // Strip out any trailing `*`.
906 if (blockListEntry.endsWith("*")) {
907 blockListEntry = blockListEntry.substring(0, blockListEntry.length() - 1);
910 if (blockListEntry.contains("*")) { // Entries that contain a `*` in the middle have to be treated specially.
911 int wildcardIndex = blockListEntry.indexOf("*");
913 String firstEntry = blockListEntry.substring(0, wildcardIndex);
914 String secondEntry = blockListEntry.substring(wildcardIndex + 1);
916 // Remove `.*` if it appears at the beginning of the second entry.
917 if (secondEntry.startsWith(".*")) {
918 secondEntry = secondEntry.substring(2);
921 // Create a third entry if required.
922 if (secondEntry.contains("*")) {
923 wildcardIndex = secondEntry.indexOf("*");
925 String thirdEntry = secondEntry.substring(wildcardIndex + 1);
926 secondEntry = secondEntry.substring(0, wildcardIndex);
928 String[] tripleEntry = {firstEntry, secondEntry, thirdEntry};
930 multiEntryBlockList.add(tripleEntry);
932 //Log.i("BlockLists", "Multi entry tripple block list added: " + firstEntry + " , " + secondEntry + " , " + thirdEntry);
934 if (firstEntry.startsWith("|")) {
935 String[] doubleEntry = {firstEntry.substring(1), secondEntry};
937 multiEntryInitialBlockList.add(doubleEntry);
939 //Log.i("BlockLists", "Multi entry initial block list added: " + firstEntry.substring(1) + " , " + secondEntry);
941 String[] doubleEntry = {firstEntry, secondEntry};
943 multiEntryBlockList.add(doubleEntry);
945 //Log.i("BlockLists", "Multi entry block list added: " + firstEntry + " , " + secondEntry);
948 } else { // This is a basic entry.
949 // Add the modified block list entry to the main block list.
950 mainBlockList.add(blockListEntry);
952 //Log.i("BlockLists", "Main block list added: " + blockListEntry);
957 // Close `bufferedReader`.
958 bufferedReader.close();
959 } catch (IOException e) {
960 // The asset exists, so the `IOException` will never be thrown.
963 Log.i("BlockLists", "Finish populating block lists");
965 // Set the content view.
966 setContentView(R.layout.main_drawerlayout);
968 // Get a handle for `inputMethodManager`.
969 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
971 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
972 supportAppBar = findViewById(R.id.app_bar);
973 setSupportActionBar(supportAppBar);
974 appBar = getSupportActionBar();
976 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
977 assert appBar != null;
979 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
980 appBar.setCustomView(R.layout.url_app_bar);
981 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
983 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
984 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
985 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
986 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
988 // Get a handle for `urlTextBox`.
989 urlTextBox = findViewById(R.id.url_edittext);
991 // Remove the formatting from `urlTextBar` when the user is editing the text.
992 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
993 if (hasFocus) { // The user is editing `urlTextBox`.
994 // Remove the highlighting.
995 urlTextBox.getText().removeSpan(redColorSpan);
996 urlTextBox.getText().removeSpan(initialGrayColorSpan);
997 urlTextBox.getText().removeSpan(finalGrayColorSpan);
998 } else { // The user has stopped editing `urlTextBox`.
999 // Reapply the highlighting.
1004 // Set the go button on the keyboard to load the URL in `urlTextBox`.
1005 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
1006 // If the event is a key-down event on the `enter` button, load the URL.
1007 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
1008 // Load the URL into the mainWebView and consume the event.
1010 loadUrlFromTextBox();
1011 } catch (UnsupportedEncodingException e) {
1012 e.printStackTrace();
1014 // If the enter key was pressed, consume the event.
1017 // If any other key was pressed, do not consume the event.
1022 // Set `waitingForOrbotHTMLString`.
1023 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
1025 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
1026 currentDomainName = "";
1027 orbotStatus = "unknown";
1028 waitingForOrbot = false;
1030 // Create an Orbot status `BroadcastReceiver`.
1031 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
1033 public void onReceive(Context context, Intent intent) {
1034 // Store the content of the status message in `orbotStatus`.
1035 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
1037 // If we are waiting on Orbot, load the website now that Orbot is connected.
1038 if (orbotStatus.equals("ON") && waitingForOrbot) {
1039 // Reset `waitingForOrbot`.
1040 waitingForOrbot = false;
1042 // Load `formattedUrlString
1043 loadUrl(formattedUrlString);
1048 // Register `orbotStatusBroadcastReceiver` on `this` context.
1049 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
1051 // Get handles for views that need to be accessed.
1052 drawerLayout = findViewById(R.id.drawerlayout);
1053 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
1054 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
1055 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
1056 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
1057 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
1058 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
1059 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
1060 mainWebView = findViewById(R.id.main_webview);
1061 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
1062 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
1063 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
1064 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
1065 favoriteIconImageView = findViewById(R.id.favorite_icon);
1067 // 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.
1069 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
1070 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
1071 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
1072 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
1074 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
1075 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
1076 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
1077 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
1080 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
1081 launchBookmarksActivityFab.setOnClickListener(v -> {
1082 // Create an intent to launch the bookmarks activity.
1083 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
1085 // Include the current folder with the `Intent`.
1086 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
1089 startActivity(bookmarksIntent);
1092 // Set the create new bookmark folder FAB to display the `AlertDialog`.
1093 createBookmarkFolderFab.setOnClickListener(v -> {
1094 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
1095 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
1096 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
1099 // Set the create new bookmark FAB to display the `AlertDialog`.
1100 createBookmarkFab.setOnClickListener(view -> {
1101 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
1102 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
1103 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
1106 // Create a double-tap listener to toggle full-screen mode.
1107 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
1108 // Override `onDoubleTap()`. All other events are handled using the default settings.
1110 public boolean onDoubleTap(MotionEvent event) {
1111 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
1112 // Toggle `inFullScreenBrowsingMode`.
1113 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
1115 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
1116 // Hide the `appBar`.
1119 // Hide the `BannerAd` in the free flavor.
1120 if (BuildConfig.FLAVOR.contentEquals("free")) {
1121 BannerAd.hideAd(adView);
1124 // Modify the system bars.
1125 if (hideSystemBarsOnFullscreen) { // Hide everything.
1126 // Remove the translucent overlays.
1127 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1129 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1130 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1132 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1133 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1134 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1136 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1138 // Set `rootCoordinatorLayout` to fill the whole screen.
1139 rootCoordinatorLayout.setFitsSystemWindows(false);
1140 } else { // Hide everything except the status and navigation bars.
1141 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
1142 rootCoordinatorLayout.setFitsSystemWindows(false);
1144 // 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.
1145 if (translucentNavigationBarOnFullscreen) {
1146 // Set the navigation bar to be translucent.
1147 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1150 } else { // Switch to normal viewing mode.
1151 // Show the `appBar`.
1154 // Show the `BannerAd` in the free flavor.
1155 if (BuildConfig.FLAVOR.contentEquals("free")) {
1156 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1157 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1159 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1160 adView = findViewById(R.id.adview);
1163 // Remove the translucent navigation bar flag if it is set.
1164 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1166 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1167 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1169 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
1170 rootCoordinatorLayout.setSystemUiVisibility(0);
1172 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
1173 rootCoordinatorLayout.setFitsSystemWindows(true);
1176 // Consume the double-tap.
1178 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
1184 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
1185 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
1186 // Call `performClick()` on the view, which is required for accessibility.
1189 // Send the `event` to `gestureDetector`.
1190 return gestureDetector.onTouchEvent(event);
1193 // Update `findOnPageCountTextView`.
1194 mainWebView.setFindListener(new WebView.FindListener() {
1195 // Get a handle for `findOnPageCountTextView`.
1196 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
1199 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
1200 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
1201 // Set `findOnPageCountTextView` to `0/0`.
1202 findOnPageCountTextView.setText(R.string.zero_of_zero);
1203 } else if (isDoneCounting) { // There are matches.
1204 // `activeMatchOrdinal` is zero-based.
1205 int activeMatch = activeMatchOrdinal + 1;
1207 // Build the match string.
1208 String matchString = activeMatch + "/" + numberOfMatches;
1210 // Set `findOnPageCountTextView`.
1211 findOnPageCountTextView.setText(matchString);
1216 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
1217 findOnPageEditText.addTextChangedListener(new TextWatcher() {
1219 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
1224 public void onTextChanged(CharSequence s, int start, int before, int count) {
1229 public void afterTextChanged(Editable s) {
1230 // Search for the text in `mainWebView`.
1231 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
1235 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
1236 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
1237 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
1238 // Hide the soft keyboard. `0` indicates no additional flags.
1239 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1241 // Consume the event.
1243 } else { // A different key was pressed.
1244 // Do not consume the event.
1249 // Implement swipe to refresh
1250 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
1251 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
1252 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
1254 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
1255 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
1256 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
1258 // Listen for touches on the navigation menu.
1259 final NavigationView navigationView = findViewById(R.id.navigationview);
1260 navigationView.setNavigationItemSelectedListener(this);
1262 // 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.
1263 final Menu navigationMenu = navigationView.getMenu();
1264 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
1265 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
1266 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
1268 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
1269 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
1270 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
1272 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
1273 currentBookmarksFolder = "";
1275 // Load the home folder, which is `""` in the database.
1276 loadBookmarksFolder();
1278 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
1279 // Convert the id from long to int to match the format of the bookmarks database.
1280 int databaseID = (int) id;
1282 // Get the bookmark `Cursor` for this ID and move it to the first row.
1283 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
1284 bookmarkCursor.moveToFirst();
1286 // Act upon the bookmark according to the type.
1287 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
1288 // Store the new folder name in `currentBookmarksFolder`.
1289 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
1291 // Load the new folder.
1292 loadBookmarksFolder();
1293 } else { // The selected bookmark is not a folder.
1294 // Load the bookmark URL.
1295 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
1297 // Close the bookmarks drawer.
1298 drawerLayout.closeDrawer(GravityCompat.END);
1301 // Close the `Cursor`.
1302 bookmarkCursor.close();
1305 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
1306 // Convert the database ID from `long` to `int`.
1307 int databaseId = (int) id;
1309 // Find out if the selected bookmark is a folder.
1310 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
1313 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
1314 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
1316 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
1317 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
1318 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
1320 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
1321 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
1322 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
1325 // Consume the event.
1329 // The `DrawerListener` allows us to update the Navigation Menu.
1330 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
1332 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
1336 public void onDrawerOpened(@NonNull View drawerView) {
1340 public void onDrawerClosed(@NonNull View drawerView) {
1344 public void onDrawerStateChanged(int newState) {
1345 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
1346 // Update the `Back`, `Forward`, and `History` menu items.
1347 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
1348 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
1349 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
1351 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
1352 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1354 // Clear the focus from `urlTextBox` if it has it.
1355 urlTextBox.clearFocus();
1360 // drawerToggle creates the hamburger icon at the start of the AppBar.
1361 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
1363 mainWebView.setWebViewClient(new WebViewClient() {
1364 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
1365 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
1366 @SuppressWarnings("deprecation")
1368 public boolean shouldOverrideUrlLoading(WebView view, String url) {
1369 if (url.startsWith("mailto:")) { // Load the email address in an external email program.
1370 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1371 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1373 // Parse the url and set it as the data for the `Intent`.
1374 emailIntent.setData(Uri.parse(url));
1376 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1377 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1380 startActivity(emailIntent);
1382 // Returning `true` indicates the application is handling the URL.
1384 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
1385 // `ACTION_DIAL` open the dialer and loads the phone number, but waits for the user to place the call.
1386 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
1388 // Add the phone number to the intent.
1389 dialIntent.setData(Uri.parse(url));
1391 // `FLAG_ACTIVITY_NEW_TASK` opens the dialer in a new task instead as part of Privacy Browser.
1392 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1395 startActivity(dialIntent);
1397 // Returning `true` indicates the application is handling the URL.
1399 } else { // Load the URL in Privacy Browser.
1400 // Apply the domain settings for the new URL.
1401 applyDomainSettings(url);
1403 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
1408 // Check requests against the block lists. The deprecated `shouldInterceptRequest` must be used until minimum API >= 21.
1409 @SuppressWarnings("deprecation")
1411 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
1412 if (adBlockerEnabled) { // Check the block lists.
1413 Log.i("BlockLists", "Begin check for " + url);
1415 Uri currentUri = Uri.parse(formattedUrlString);
1416 String currentDomain = currentUri.getHost();
1418 Uri requestUri = Uri.parse(url);
1419 String requestDomain = requestUri.getHost();
1421 boolean thirdPartyRequest = !requestDomain.equals(currentDomain);
1423 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
1425 for (String whiteListEntry : mainWhiteList) {
1426 if (url.contains(whiteListEntry)) {
1427 Log.i("BlockLists", "Request allowed by main white list: " + whiteListEntry + " | " + url);
1429 // `Return null` loads the requested resource.
1434 for (String[] whiteListEntry : multiEntryWhiteList) {
1435 if (whiteListEntry.length == 2) { // There are two entries.
1436 if (url.contains(whiteListEntry[0]) && url.contains(whiteListEntry[1])) {
1437 Log.i("BlockLists", "Request allowed by multi entry white list: " + whiteListEntry[0] + " , " + whiteListEntry[1] + " | " + url);
1439 // `Return null` loads the requested resource.
1442 } else { // There are three entries.
1443 if (url.contains(whiteListEntry[0]) && url.contains(whiteListEntry[1]) && url.contains(whiteListEntry[2])) {
1444 Log.i("BlockLists", "Request allowed by multi entry white list: " + whiteListEntry[0] + " , " + whiteListEntry[1] + " , " + whiteListEntry[2] + " | " + url);
1446 // `Return null` loads the requested resource.
1452 for (String[] whiteListEntry : domainWhiteList) {
1453 if (requestDomain.endsWith(whiteListEntry[0]) && url.contains(whiteListEntry[1])) {
1454 Log.i("BlockLists", "Request allowed by domain white list: " + whiteListEntry[0] + " , " + whiteListEntry[1] + " | " + url);
1456 // `Return null` loads the requested resource.
1461 // Only check the third-party white lists if this is a third-party request.
1462 if (thirdPartyRequest) {
1463 for (String[] whiteListEntry : thirdPartyDomainWhiteList) {
1464 if (requestDomain.endsWith(whiteListEntry[0]) && url.contains(whiteListEntry[1])) {
1465 Log.i("BlockLists", "Request allowed by third-party domain white list: " + whiteListEntry[0] + " , " + whiteListEntry[1] + " | " + url);
1467 // `Return null` loads the requested resource.
1473 for (String blockListEntry : mainBlockList) {
1474 if (url.contains(blockListEntry)) {
1475 Log.i("BlockLists", "Request blocked by main block list: " + blockListEntry + " | " + url);
1477 // Return an empty `WebResourceResponse`.
1478 return emptyWebResourceResponse;
1482 for (String blockListEntry : initialBlockList) {
1483 if (url.startsWith(blockListEntry)) {
1484 Log.i("BlockLists", "Request blocked by initial block list: " + blockListEntry + " | " + url);
1486 // Return an empty `WebResourceResponse`.
1487 return emptyWebResourceResponse;
1491 for (String blockListEntry : finalBlockList) {
1492 if (url.endsWith(blockListEntry)) {
1493 Log.i("BlockLists", "Request blocked by final block list: " + blockListEntry + " | " + url);
1495 // Return an empty `WebResourceResponse`.
1496 return emptyWebResourceResponse;
1500 for (String[] blockListEntry : multiEntryBlockList) {
1501 if (blockListEntry.length == 2) { // There are two entries.
1502 if (url.contains(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1503 Log.i("BlockLists", "Request blocked by multi entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1505 // Return an empty `WebResourceResponse`.
1506 return emptyWebResourceResponse;
1508 } else { // There are three entries.
1509 if (url.contains(blockListEntry[0]) && url.contains(blockListEntry[1]) && url.contains(blockListEntry[2])) {
1510 Log.i("BlockLists", "Request blocked by multi entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " , " + blockListEntry[2] + " | " + url);
1512 // Return an empty `WebResourceResponse`.
1513 return emptyWebResourceResponse;
1518 for (String[] blockListEntry : multiEntryInitialBlockList) {
1519 if (url.startsWith(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1520 Log.i("BlockLists", "Request blocked by multi entry initial block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1522 // Return an empty `WebResourceResponse`.
1523 return emptyWebResourceResponse;
1527 for (String[] blockListEntry : multiEntryFinalBlockList) {
1528 if (url.contains(blockListEntry[0]) && url.endsWith(blockListEntry[1])) {
1529 Log.i("BlockLists", "Request blocked by multi entry final block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1531 // Return an empty `WebResourceResponse`.
1532 return emptyWebResourceResponse;
1536 for (String[] blockListEntry : domainBlockList) {
1537 if (blockListEntry.length == 2) { // There is one entry.
1538 if (requestDomain.endsWith(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1539 Log.i("BlockLists", "Request blocked by domain block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1541 // Return an empty `WebResourceResponse`.
1542 return emptyWebResourceResponse;
1544 } else { // There are two entries.
1545 if (requestDomain.endsWith(blockListEntry[0]) && url.contains(blockListEntry[1]) && url.contains(blockListEntry[2])) {
1546 Log.i("BlockLists", "Request blocked by domain block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " , " + blockListEntry[2] + " | " + url);
1548 // Return an empty `WebResourceResponse`.
1549 return emptyWebResourceResponse;
1554 for (String[] blockListEntry : domainInitialBlockList) {
1555 if (requestDomain.endsWith(blockListEntry[0]) && url.startsWith(blockListEntry[1])) {
1556 Log.i("BlockLists", "Request blocked by domain initial block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1558 // Return an empty `WebResourceResponse`.
1559 return emptyWebResourceResponse;
1563 for (String[] blockListEntry : domainFinalBlockList) {
1564 if (requestDomain.endsWith(blockListEntry[0]) && url.endsWith(blockListEntry[2])) {
1565 Log.i("BlockLists", "Request blocked by domain final block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1567 // Return an empty `WebResourceResponse`.
1568 return emptyWebResourceResponse;
1572 for (String[] blockListEntry : domainRegularExpressionBlockList) {
1573 if (requestDomain.endsWith(blockListEntry[0]) && Pattern.matches(blockListEntry[1], url)) {
1574 Log.i("BlockLists", "Request blocked by domain regular expression block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1576 // Return an empty `WebResourceResponse`.
1577 return emptyWebResourceResponse;
1581 // Only check the third-party block lists if this is a third-party request.
1582 if (thirdPartyRequest) {
1583 for (String blockListEntry : thirdPartyBlockList) {
1584 if (url.contains(blockListEntry)) {
1585 Log.i("BlockLists", "Request blocked by third-party block list: " + blockListEntry + " | " + url);
1587 // Return an empty `WebResourceResponse`.
1588 return emptyWebResourceResponse;
1592 for (String blockListEntry : thirdPartyInitialBlockList) {
1593 if (url.startsWith(blockListEntry)) {
1594 Log.i("BlockLists", "Request blocked by third-party initial block list: " + blockListEntry + " | " + url);
1596 // Return an empty `WebResourceResponse`.
1597 return emptyWebResourceResponse;
1601 for (String[] blockListEntry : thirdPartyMultiEntryBlockList) {
1602 switch (blockListEntry.length) {
1603 case 2: // There are two entries.
1604 if (url.contains(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1605 Log.i("BlockLists", "Request blocked by third-party multi-entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1607 // Return an empty `WebResourceResponse`.
1608 return emptyWebResourceResponse;
1612 case 3: // There are three entries.
1613 if (url.contains(blockListEntry[0]) && url.contains(blockListEntry[1]) && url.contains(blockListEntry[2])) {
1614 Log.i("BlockLists", "Request blocked by third-party multi-entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " , " + blockListEntry[2] +
1617 // Return an empty `WebResourceResponse`.
1618 return emptyWebResourceResponse;
1622 case 4: // There are four entries.
1623 if (url.contains(blockListEntry[0]) && url.contains(blockListEntry[1]) && url.contains(blockListEntry[2]) && url.contains(blockListEntry[3])) {
1624 Log.i("BlockLists", "Request blocked by third-party multi-entry block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " , " + blockListEntry[2] +
1625 " , " + blockListEntry[3] + " | " + url);
1627 // Return an empty `WebResourceResponse`.
1628 return emptyWebResourceResponse;
1634 for (String[] blockListEntry : thirdPartyMultiEntryInitialBlockList) {
1635 if (url.startsWith(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1636 Log.i("BlockLists", "Request blocked by third-party multi-entry initial block list");
1638 // Return an empty `WebResourceResponse`.
1639 return emptyWebResourceResponse;
1643 for (String[] blockListEntry : thirdPartyDomainBlockList) {
1644 if (blockListEntry.length == 2) { // There is one entry.
1645 if (requestDomain.endsWith(blockListEntry[0]) && url.contains(blockListEntry[1])) {
1646 Log.i("BlockLists", "Request blocked by third-party domain block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " | " + url);
1648 // Return an empty `WebResourceResponse`.
1649 return emptyWebResourceResponse;
1651 } else { // There are two entries.
1652 if (requestDomain.endsWith(blockListEntry[0]) && url.contains(blockListEntry[1]) && url.contains(blockListEntry[2])) {
1653 Log.i("BlockLists", "Request blocked by third-party domain block list: " + blockListEntry[0] + " , " + blockListEntry[1] + " , " + blockListEntry[2] + " | " +
1656 // Return an empty `WebResourceResponse`.
1657 return emptyWebResourceResponse;
1662 for (String blockListEntry : thirdPartyRegularExpressionBlockList) {
1663 if (Pattern.matches(blockListEntry, url)) {
1664 Log.i("BlockLists", "Request blocked by third-party regular expression block list: " + blockListEntry + " | " + url);
1666 // Return an empty `WebResourceResponse`.
1667 return emptyWebResourceResponse;
1672 for (String blockListEntry : regularExpressionBlockList) {
1673 if (Pattern.matches(blockListEntry, url)) {
1674 Log.i("BlockLists", "Request blocked by regular expression block list: " + blockListEntry + " | " + url);
1676 // Return an empty `WebResourceResponse`.
1677 return emptyWebResourceResponse;
1681 Log.i("BlockLists", "End check for " + url);
1683 // `return null` loads the requested resource.
1685 } else { // Ad blocking is disabled.
1686 // `return null` loads the requested resource.
1691 // Handle HTTP authentication requests.
1693 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
1694 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
1695 httpAuthHandler = handler;
1697 // Display the HTTP authentication dialog.
1698 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
1699 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
1702 // Update the URL in urlTextBox when the page starts to load.
1704 public void onPageStarted(WebView view, String url, Bitmap favicon) {
1705 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
1707 mainWebView.setVisibility(View.INVISIBLE);
1710 // Hide the keyboard. `0` indicates no additional flags.
1711 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1713 // Check to see if we are waiting on Orbot.
1714 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
1715 // 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.
1716 formattedUrlString = url;
1718 // Display the formatted URL text.
1719 urlTextBox.setText(formattedUrlString);
1721 // Apply text highlighting to `urlTextBox`.
1724 // Apply any custom domain settings if the URL was loaded by navigating history.
1725 if (navigatingHistory) {
1726 applyDomainSettings(url);
1729 // 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.
1730 urlIsLoading = true;
1734 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
1736 public void onPageFinished(WebView view, String url) {
1737 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
1738 urlIsLoading = false;
1740 // Clear the cache and history if Incognito Mode is enabled.
1741 if (incognitoModeEnabled) {
1742 // Clear the cache. `true` includes disk files.
1743 mainWebView.clearCache(true);
1745 // Clear the back/forward history.
1746 mainWebView.clearHistory();
1748 // Manually delete cache folders.
1750 // Delete the main `cache` folder.
1751 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1753 // 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`.
1754 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1755 } catch (IOException e) {
1756 // Do nothing if an error is thrown.
1760 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
1761 if (!waitingForOrbot) {
1762 // Check to see if `WebView` has set `url` to be `about:blank`.
1763 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
1764 // Set `formattedUrlString` to `""`.
1765 formattedUrlString = "";
1767 urlTextBox.setText(formattedUrlString);
1769 // Request focus for `urlTextBox`.
1770 urlTextBox.requestFocus();
1772 // Display the keyboard.
1773 inputMethodManager.showSoftInput(urlTextBox, 0);
1775 // Apply the domain settings. This clears any settings from the previous domain.
1776 applyDomainSettings(formattedUrlString);
1777 } else { // `WebView` has loaded a webpage.
1778 // Set `formattedUrlString`.
1779 formattedUrlString = url;
1781 // Only update `urlTextBox` if the user is not typing in it.
1782 if (!urlTextBox.hasFocus()) {
1783 // Display the formatted URL text.
1784 urlTextBox.setText(formattedUrlString);
1786 // Apply text highlighting to `urlTextBox`.
1791 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1792 sslCertificate = mainWebView.getCertificate();
1794 // 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.
1795 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1796 // Initialize the current SSL certificate variables.
1797 String currentWebsiteIssuedToCName = "";
1798 String currentWebsiteIssuedToOName = "";
1799 String currentWebsiteIssuedToUName = "";
1800 String currentWebsiteIssuedByCName = "";
1801 String currentWebsiteIssuedByOName = "";
1802 String currentWebsiteIssuedByUName = "";
1803 Date currentWebsiteSslStartDate = null;
1804 Date currentWebsiteSslEndDate = null;
1807 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1808 if (sslCertificate != null) {
1809 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1810 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1811 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1812 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1813 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1814 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1815 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1816 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1819 // 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`.
1820 String currentWebsiteSslStartDateString = "";
1821 String currentWebsiteSslEndDateString = "";
1822 String pinnedDomainSslStartDateString = "";
1823 String pinnedDomainSslEndDateString = "";
1825 // Convert the `Dates` to `Strings` if they are not `null`.
1826 if (currentWebsiteSslStartDate != null) {
1827 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1830 if (currentWebsiteSslEndDate != null) {
1831 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1834 if (pinnedDomainSslStartDate != null) {
1835 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1838 if (pinnedDomainSslEndDate != null) {
1839 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1842 // Check to see if the pinned SSL certificate matches the current website certificate.
1843 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1844 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1845 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1846 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1847 // The pinned SSL certificate doesn't match the current domain certificate.
1848 //Display the pinned SSL certificate mismatch `AlertDialog`.
1849 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1850 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1856 // Handle SSL Certificate errors.
1858 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1859 // Get the current website SSL certificate.
1860 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1862 // Extract the individual pieces of information from the current website SSL certificate.
1863 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1864 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1865 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1866 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1867 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1868 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1869 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1870 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1872 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1873 if (pinnedDomainSslCertificate &&
1874 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1875 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1876 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1877 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1878 // An SSL certificate is pinned and matches the current domain certificate.
1879 // Proceed to the website without displaying an error.
1881 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1882 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1883 sslErrorHandler = handler;
1885 // Display the SSL error `AlertDialog`.
1886 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1887 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1892 // Get a handle for the progress bar.
1893 final ProgressBar progressBar = findViewById(R.id.progress_bar);
1895 mainWebView.setWebChromeClient(new WebChromeClient() {
1896 // Update the progress bar when a page is loading.
1898 public void onProgressChanged(WebView view, int progress) {
1899 // Inject the night mode CSS if night mode is enabled.
1901 // `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
1902 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
1903 // `border: none` removes all borders, which can also be used to underline text.
1904 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
1905 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
1906 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
1907 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
1908 // Initialize a `Handler` to display `mainWebView`.
1909 Handler displayWebViewHandler = new Handler();
1911 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
1912 Runnable displayWebViewRunnable = () -> {
1913 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
1914 if (progressBar.getVisibility() == View.GONE) {
1915 mainWebView.setVisibility(View.VISIBLE);
1919 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
1920 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
1924 // Update the progress bar.
1925 progressBar.setProgress(progress);
1927 // Set the visibility of the progress bar.
1928 if (progress < 100) {
1929 // Show the progress bar.
1930 progressBar.setVisibility(View.VISIBLE);
1932 // Hide the progress bar.
1933 progressBar.setVisibility(View.GONE);
1935 // Display `mainWebView` if night mode is disabled.
1936 // 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
1937 // currently enabled.
1939 mainWebView.setVisibility(View.VISIBLE);
1942 //Stop the `SwipeToRefresh` indicator if it is running
1943 swipeRefreshLayout.setRefreshing(false);
1947 // Set the favorite icon when it changes.
1949 public void onReceivedIcon(WebView view, Bitmap icon) {
1950 // Only update the favorite icon if the website has finished loading.
1951 if (progressBar.getVisibility() == View.GONE) {
1952 // Save a copy of the favorite icon.
1953 favoriteIconBitmap = icon;
1955 // Place the favorite icon in the appBar.
1956 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1960 // Save a copy of the title when it changes.
1962 public void onReceivedTitle(WebView view, String title) {
1963 // Save a copy of the title.
1964 webViewTitle = title;
1967 // Enter full screen video
1969 public void onShowCustomView(View view, CustomViewCallback callback) {
1970 // Pause the ad if this is the free flavor.
1971 if (BuildConfig.FLAVOR.contentEquals("free")) {
1972 BannerAd.pauseAd(adView);
1975 // Remove the translucent overlays.
1976 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1978 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1979 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1981 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1982 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1983 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1985 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1987 // Set `rootCoordinatorLayout` to fill the entire screen.
1988 rootCoordinatorLayout.setFitsSystemWindows(false);
1990 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1991 fullScreenVideoFrameLayout.addView(view);
1992 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1995 // Exit full screen video
1996 public void onHideCustomView() {
1997 // Hide `fullScreenVideoFrameLayout`.
1998 fullScreenVideoFrameLayout.removeAllViews();
1999 fullScreenVideoFrameLayout.setVisibility(View.GONE);
2001 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2002 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2004 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
2005 rootCoordinatorLayout.setFitsSystemWindows(true);
2007 // Show the ad if this is the free flavor.
2008 if (BuildConfig.FLAVOR.contentEquals("free")) {
2009 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2010 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2012 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2013 adView = findViewById(R.id.adview);
2018 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
2019 registerForContextMenu(mainWebView);
2021 // Allow the downloading of files.
2022 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
2023 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
2024 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
2025 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2028 // Allow pinch to zoom.
2029 mainWebView.getSettings().setBuiltInZoomControls(true);
2031 // Hide zoom controls.
2032 mainWebView.getSettings().setDisplayZoomControls(false);
2034 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
2035 mainWebView.getSettings().setUseWideViewPort(true);
2037 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
2038 mainWebView.getSettings().setLoadWithOverviewMode(true);
2040 // Explicitly disable geolocation.
2041 mainWebView.getSettings().setGeolocationEnabled(false);
2043 // Initialize cookieManager.
2044 cookieManager = CookieManager.getInstance();
2046 // 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).
2047 customHeaders.put("X-Requested-With", "");
2049 // 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.
2050 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
2052 // Get the intent that started the app.
2053 final Intent launchingIntent = getIntent();
2055 // Extract the launching intent data as `launchingIntentUriData`.
2056 final Uri launchingIntentUriData = launchingIntent.getData();
2058 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
2059 if (launchingIntentUriData != null) {
2060 formattedUrlString = launchingIntentUriData.toString();
2063 // Get a handle for the `Runtime`.
2064 privacyBrowserRuntime = Runtime.getRuntime();
2066 // Store the application's private data directory.
2067 privateDataDirectoryString = getApplicationInfo().dataDir;
2068 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
2070 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
2071 inFullScreenBrowsingMode = false;
2073 // Initialize AdView for the free flavor.
2074 adView = findViewById(R.id.adview);
2076 // Initialize the privacy settings variables.
2077 javaScriptEnabled = false;
2078 firstPartyCookiesEnabled = false;
2079 thirdPartyCookiesEnabled = false;
2080 domStorageEnabled = false;
2081 saveFormDataEnabled = false;
2084 // Initialize `webViewTitle`.
2085 webViewTitle = getString(R.string.no_title);
2087 // Initialize `favoriteIconBitmap`. `ContextCompat` must be used until API >= 21.
2088 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
2089 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
2090 assert favoriteIconBitmapDrawable != null;
2091 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
2093 // If the favorite icon is null, load the default.
2094 if (favoriteIconBitmap == null) {
2095 favoriteIconBitmap = favoriteIconDefaultBitmap;
2098 // Apply the app settings from the shared preferences.
2101 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
2102 if (!waitingForOrbot) {
2103 loadUrl(formattedUrlString);
2108 protected void onNewIntent(Intent intent) {
2109 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
2112 if (intent.getData() != null) {
2113 // Get the intent data and convert it to a string.
2114 final Uri intentUriData = intent.getData();
2115 formattedUrlString = intentUriData.toString();
2118 // Close the navigation drawer if it is open.
2119 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2120 drawerLayout.closeDrawer(GravityCompat.START);
2123 // Load the website.
2124 loadUrl(formattedUrlString);
2126 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
2127 mainWebView.requestFocus();
2131 public void onRestart() {
2132 // Run the default commands.
2135 // Apply the app settings, which may have been changed in `SettingsActivity`.
2138 // Apply the domain settings if returning from the Domains Activity.
2139 if (reapplyDomainSettingsOnRestart) {
2140 // Reset `reapplyDomainSettingsOnRestart`.
2141 reapplyDomainSettingsOnRestart = false;
2143 // Reapply the domain settings.
2144 applyDomainSettings(formattedUrlString);
2147 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2148 updatePrivacyIcons(true);
2150 // Set the display webpage images mode.
2151 setDisplayWebpageImages();
2153 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
2154 if (reloadOnRestart) {
2155 // Reload `mainWebView`.
2156 mainWebView.reload();
2158 // Reset `reloadOnRestartBoolean`.
2159 reloadOnRestart = false;
2162 // Load the URL on restart to apply changes to night mode.
2163 if (loadUrlOnRestart) {
2164 // Load the current `formattedUrlString`.
2165 loadUrl(formattedUrlString);
2167 // Reset `loadUrlOnRestart.
2168 loadUrlOnRestart = false;
2172 if (restartFromBookmarksActivity) {
2173 // Close the bookmarks drawer.
2174 drawerLayout.closeDrawer(GravityCompat.END);
2176 // Reload the bookmarks drawer.
2177 loadBookmarksFolder();
2179 // Reset `restartFromBookmarksActivity`.
2180 restartFromBookmarksActivity = false;
2184 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
2186 public void onResume() {
2187 // Run the default commands.
2190 // Resume JavaScript (if enabled).
2191 mainWebView.resumeTimers();
2193 // Resume `mainWebView`.
2194 mainWebView.onResume();
2196 // Resume the adView for the free flavor.
2197 if (BuildConfig.FLAVOR.contentEquals("free")) {
2198 BannerAd.resumeAd(adView);
2203 public void onPause() {
2204 // Pause `mainWebView`.
2205 mainWebView.onPause();
2207 // Stop all JavaScript.
2208 mainWebView.pauseTimers();
2210 // Pause the adView or it will continue to consume resources in the background on the free flavor.
2211 if (BuildConfig.FLAVOR.contentEquals("free")) {
2212 BannerAd.pauseAd(adView);
2219 public boolean onCreateOptionsMenu(Menu menu) {
2220 // Inflate the menu; this adds items to the action bar if it is present.
2221 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
2223 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
2226 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
2227 updatePrivacyIcons(false);
2229 // Get handles for the menu items.
2230 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2231 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2232 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2233 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
2235 // Only display third-party cookies if SDK >= 21
2236 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
2238 // Get the shared preference values. `this` references the current context.
2239 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2241 // Set the status of the additional app bar icons. The default is `false`.
2242 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
2243 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2244 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2245 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
2246 } else { //Do not display the additional icons.
2247 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2248 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2249 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
2256 public boolean onPrepareOptionsMenu(Menu menu) {
2257 // Get handles for the menu items.
2258 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
2259 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
2260 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
2261 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
2262 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
2263 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
2264 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
2265 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
2266 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
2267 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
2268 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
2269 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
2271 // Set the text for the domain menu item.
2272 if (domainSettingsApplied) {
2273 addOrEditDomain.setTitle(R.string.edit_domain_settings);
2275 addOrEditDomain.setTitle(R.string.add_domain_settings);
2278 // Set the status of the menu item checkboxes.
2279 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
2280 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
2281 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
2282 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
2283 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
2285 // Enable third-party cookies if first-party cookies are enabled.
2286 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
2288 // Enable `DOM Storage` if JavaScript is enabled.
2289 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
2291 // Enable `Clear Cookies` if there are any.
2292 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
2294 // Get a count of the number of files in the `Local Storage` directory.
2295 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
2296 int localStorageDirectoryNumberOfFiles = 0;
2297 if (localStorageDirectory.exists()) {
2298 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
2301 // Get a count of the number of files in the `IndexedDB` directory.
2302 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
2303 int indexedDBDirectoryNumberOfFiles = 0;
2304 if (indexedDBDirectory.exists()) {
2305 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
2308 // Enable `Clear DOM Storage` if there is any.
2309 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
2311 // Enable `Clear Form Data` is there is any.
2312 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
2313 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
2315 // Enable `Clear Data` if any of the submenu items are enabled.
2316 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
2318 // Initialize font size variables.
2319 int fontSize = mainWebView.getSettings().getTextZoom();
2320 String fontSizeTitle;
2321 MenuItem selectedFontSizeMenuItem;
2323 // Prepare the font size title and current size menu item.
2326 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
2327 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
2331 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
2332 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
2336 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
2337 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
2341 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2342 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2346 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
2347 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
2351 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
2352 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
2356 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
2357 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
2361 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
2362 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
2366 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
2367 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
2371 // Set the font size title and select the current size menu item.
2372 fontSizeMenuItem.setTitle(fontSizeTitle);
2373 selectedFontSizeMenuItem.setChecked(true);
2375 // Only show `Refresh` if `swipeToRefresh` is disabled.
2376 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
2378 // Run all the other default commands.
2379 super.onPrepareOptionsMenu(menu);
2381 // Display the menu.
2386 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
2387 @SuppressLint("SetJavaScriptEnabled")
2388 // removeAllCookies is deprecated, but it is required for API < 21.
2389 @SuppressWarnings("deprecation")
2390 public boolean onOptionsItemSelected(MenuItem menuItem) {
2391 // Get the selected menu item ID.
2392 int menuItemId = menuItem.getItemId();
2394 // Set the commands that relate to the menu entries.
2395 switch (menuItemId) {
2396 case R.id.add_or_edit_domain:
2397 if (domainSettingsApplied) { // Edit the current domain settings.
2398 // Reapply the domain settings on returning to `MainWebViewActivity`.
2399 reapplyDomainSettingsOnRestart = true;
2400 currentDomainName = "";
2402 // Create an intent to launch the domains activity.
2403 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2405 // Put extra information instructing the domains activity to directly load the current domain.
2406 domainsIntent.putExtra("LoadDomain", domainSettingsDatabaseId);
2409 startActivity(domainsIntent);
2410 } else { // Add a new domain.
2411 // Show the add domain `AlertDialog`.
2412 AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
2413 addDomainDialog.show(getSupportFragmentManager(), getResources().getString(R.string.add_domain));
2417 case R.id.toggle_javascript:
2418 // Switch the status of javaScriptEnabled.
2419 javaScriptEnabled = !javaScriptEnabled;
2421 // Apply the new JavaScript status.
2422 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2424 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2425 updatePrivacyIcons(true);
2427 // Display a `Snackbar`.
2428 if (javaScriptEnabled) { // JavaScrip is enabled.
2429 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
2430 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
2431 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
2432 } else { // Privacy mode.
2433 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2436 // Reload the WebView.
2437 mainWebView.reload();
2440 case R.id.toggle_first_party_cookies:
2441 // Switch the status of firstPartyCookiesEnabled.
2442 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
2444 // Update the menu checkbox.
2445 menuItem.setChecked(firstPartyCookiesEnabled);
2447 // Apply the new cookie status.
2448 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2450 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2451 updatePrivacyIcons(true);
2453 // Display a `Snackbar`.
2454 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2455 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2456 } else if (javaScriptEnabled){ // JavaScript is still enabled.
2457 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2458 } else { // Privacy mode.
2459 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
2462 // Reload the WebView.
2463 mainWebView.reload();
2466 case R.id.toggle_third_party_cookies:
2467 if (Build.VERSION.SDK_INT >= 21) {
2468 // Switch the status of thirdPartyCookiesEnabled.
2469 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
2471 // Update the menu checkbox.
2472 menuItem.setChecked(thirdPartyCookiesEnabled);
2474 // Apply the new cookie status.
2475 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2477 // Display a `Snackbar`.
2478 if (thirdPartyCookiesEnabled) {
2479 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
2481 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
2484 // Reload the WebView.
2485 mainWebView.reload();
2486 } // Else do nothing because SDK < 21.
2489 case R.id.toggle_dom_storage:
2490 // Switch the status of domStorageEnabled.
2491 domStorageEnabled = !domStorageEnabled;
2493 // Update the menu checkbox.
2494 menuItem.setChecked(domStorageEnabled);
2496 // Apply the new DOM Storage status.
2497 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2499 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2500 updatePrivacyIcons(true);
2502 // Display a `Snackbar`.
2503 if (domStorageEnabled) {
2504 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
2506 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
2509 // Reload the WebView.
2510 mainWebView.reload();
2513 case R.id.toggle_save_form_data:
2514 // Switch the status of saveFormDataEnabled.
2515 saveFormDataEnabled = !saveFormDataEnabled;
2517 // Update the menu checkbox.
2518 menuItem.setChecked(saveFormDataEnabled);
2520 // Apply the new form data status.
2521 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2523 // Display a `Snackbar`.
2524 if (saveFormDataEnabled) {
2525 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
2527 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
2530 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
2531 updatePrivacyIcons(true);
2533 // Reload the WebView.
2534 mainWebView.reload();
2537 case R.id.clear_cookies:
2538 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
2539 .setAction(R.string.undo, v -> {
2540 // Do nothing because everything will be handled by `onDismissed()` below.
2542 .addCallback(new Snackbar.Callback() {
2544 public void onDismissed(Snackbar snackbar, int event) {
2546 // The user pushed the `Undo` button.
2547 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2551 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2553 // `cookieManager.removeAllCookie()` varies by SDK.
2554 if (Build.VERSION.SDK_INT < 21) {
2555 cookieManager.removeAllCookie();
2557 // `null` indicates no callback.
2558 cookieManager.removeAllCookies(null);
2566 case R.id.clear_dom_storage:
2567 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
2568 .setAction(R.string.undo, v -> {
2569 // Do nothing because everything will be handled by `onDismissed()` below.
2571 .addCallback(new Snackbar.Callback() {
2573 public void onDismissed(Snackbar snackbar, int event) {
2575 // The user pushed the `Undo` button.
2576 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2580 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2582 // Delete the DOM Storage.
2583 WebStorage webStorage = WebStorage.getInstance();
2584 webStorage.deleteAllData();
2586 // Manually delete the DOM storage files and directories.
2588 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2589 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2591 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2592 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2593 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2594 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2595 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2596 } catch (IOException e) {
2597 // Do nothing if an error is thrown.
2605 case R.id.clear_form_data:
2606 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
2607 .setAction(R.string.undo, v -> {
2608 // Do nothing because everything will be handled by `onDismissed()` below.
2610 .addCallback(new Snackbar.Callback() {
2612 public void onDismissed(Snackbar snackbar, int event) {
2614 // The user pushed the `Undo` button.
2615 case Snackbar.Callback.DISMISS_EVENT_ACTION:
2619 // The `Snackbar` was dismissed without the `Undo` button being pushed.
2621 // Delete the form data.
2622 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
2623 mainWebViewDatabase.clearFormData();
2630 case R.id.font_size_twenty_five_percent:
2631 mainWebView.getSettings().setTextZoom(25);
2634 case R.id.font_size_fifty_percent:
2635 mainWebView.getSettings().setTextZoom(50);
2638 case R.id.font_size_seventy_five_percent:
2639 mainWebView.getSettings().setTextZoom(75);
2642 case R.id.font_size_one_hundred_percent:
2643 mainWebView.getSettings().setTextZoom(100);
2646 case R.id.font_size_one_hundred_twenty_five_percent:
2647 mainWebView.getSettings().setTextZoom(125);
2650 case R.id.font_size_one_hundred_fifty_percent:
2651 mainWebView.getSettings().setTextZoom(150);
2654 case R.id.font_size_one_hundred_seventy_five_percent:
2655 mainWebView.getSettings().setTextZoom(175);
2658 case R.id.font_size_two_hundred_percent:
2659 mainWebView.getSettings().setTextZoom(200);
2662 case R.id.display_images:
2663 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
2664 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2665 mainWebView.reload();
2666 } else { // Images are not currently loaded automatically.
2667 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2670 // Set `onTheFlyDisplayImagesSet`.
2671 onTheFlyDisplayImagesSet = true;
2675 // Setup the share string.
2676 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
2678 // Create the share intent.
2679 Intent shareIntent = new Intent();
2680 shareIntent.setAction(Intent.ACTION_SEND);
2681 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
2682 shareIntent.setType("text/plain");
2685 startActivity(Intent.createChooser(shareIntent, "Share URL"));
2688 case R.id.find_on_page:
2689 // Hide the URL app bar.
2690 supportAppBar.setVisibility(View.GONE);
2692 // Show the Find on Page `RelativeLayout`.
2693 findOnPageLinearLayout.setVisibility(View.VISIBLE);
2695 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
2696 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
2697 findOnPageEditText.postDelayed(() -> {
2698 // Set the focus on `findOnPageEditText`.
2699 findOnPageEditText.requestFocus();
2701 // Display the keyboard. `0` sets no input flags.
2702 inputMethodManager.showSoftInput(findOnPageEditText, 0);
2707 // Get a `PrintManager` instance.
2708 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
2710 // Convert `mainWebView` to `printDocumentAdapter`.
2711 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
2713 // Remove the lint error below that `printManager` might be `null`.
2714 assert printManager != null;
2716 // Print the document. The print attributes are `null`.
2717 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
2720 case R.id.view_source:
2721 // Launch the Vew Source activity.
2722 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
2723 startActivity(viewSourceIntent);
2726 case R.id.add_to_homescreen:
2727 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
2728 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
2729 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
2731 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
2735 mainWebView.reload();
2739 // Don't consume the event.
2740 return super.onOptionsItemSelected(menuItem);
2744 // removeAllCookies is deprecated, but it is required for API < 21.
2745 @SuppressWarnings("deprecation")
2747 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
2748 int menuItemId = menuItem.getItemId();
2750 switch (menuItemId) {
2756 if (mainWebView.canGoBack()) {
2757 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2758 navigatingHistory = true;
2760 // Load the previous website in the history.
2761 mainWebView.goBack();
2766 if (mainWebView.canGoForward()) {
2767 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2768 navigatingHistory = true;
2770 // Load the next website in the history.
2771 mainWebView.goForward();
2776 // Get the `WebBackForwardList`.
2777 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
2779 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
2780 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2781 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2784 case R.id.downloads:
2785 // Launch the system Download Manager.
2786 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2788 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2789 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2791 startActivity(downloadManagerIntent);
2795 // Reapply the domain settings on returning to `MainWebViewActivity`.
2796 reapplyDomainSettingsOnRestart = true;
2797 currentDomainName = "";
2799 // Launch `DomainsActivity`.
2800 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2801 startActivity(domainsIntent);
2805 // Reapply the domain settings on returning to `MainWebViewActivity`.
2806 reapplyDomainSettingsOnRestart = true;
2807 currentDomainName = "";
2809 // Launch `SettingsActivity`.
2810 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2811 startActivity(settingsIntent);
2815 // Launch `GuideActivity`.
2816 Intent guideIntent = new Intent(this, GuideActivity.class);
2817 startActivity(guideIntent);
2821 // Launch `AboutActivity`.
2822 Intent aboutIntent = new Intent(this, AboutActivity.class);
2823 startActivity(aboutIntent);
2826 case R.id.clearAndExit:
2827 // Get a handle for `sharedPreferences`. `this` references the current context.
2828 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2830 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2833 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2834 // The command to remove cookies changed slightly in API 21.
2835 if (Build.VERSION.SDK_INT >= 21) {
2836 cookieManager.removeAllCookies(null);
2838 cookieManager.removeAllCookie();
2841 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2843 // We have to use two commands because `Runtime.exec()` does not like `*`.
2844 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2845 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2846 } catch (IOException e) {
2847 // Do nothing if an error is thrown.
2851 // Clear DOM storage.
2852 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2853 // Ask `WebStorage` to clear the DOM storage.
2854 WebStorage webStorage = WebStorage.getInstance();
2855 webStorage.deleteAllData();
2857 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2859 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2860 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2862 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2863 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2864 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2865 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2866 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2867 } catch (IOException e) {
2868 // Do nothing if an error is thrown.
2873 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2874 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2875 webViewDatabase.clearFormData();
2877 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2879 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2880 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2881 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2882 } catch (IOException e) {
2883 // Do nothing if an error is thrown.
2888 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2889 // `true` includes disk files.
2890 mainWebView.clearCache(true);
2892 // Manually delete the cache directories.
2894 // Delete the main cache directory.
2895 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2896 // Delete the secondary `Service Worker` cache directory.
2897 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2898 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2899 } catch (IOException e) {
2900 // Do nothing if an error is thrown.
2904 // Clear SSL certificate preferences.
2905 mainWebView.clearSslPreferences();
2907 // Clear the back/forward history.
2908 mainWebView.clearHistory();
2910 // Clear `formattedUrlString`.
2911 formattedUrlString = null;
2913 // Clear `customHeaders`.
2914 customHeaders.clear();
2916 // Detach all views from `mainWebViewRelativeLayout`.
2917 mainWebViewRelativeLayout.removeAllViews();
2919 // Destroy the internal state of `mainWebView`.
2920 mainWebView.destroy();
2922 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2923 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2924 if (clearEverything) {
2926 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2927 } catch (IOException e) {
2928 // Do nothing if an error is thrown.
2932 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2933 if (Build.VERSION.SDK_INT >= 21) {
2934 finishAndRemoveTask();
2939 // Remove the terminated program from RAM. The status code is `0`.
2944 // Close the navigation drawer.
2945 drawerLayout.closeDrawer(GravityCompat.START);
2950 public void onPostCreate(Bundle savedInstanceState) {
2951 super.onPostCreate(savedInstanceState);
2953 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2954 drawerToggle.syncState();
2958 public void onConfigurationChanged(Configuration newConfig) {
2959 super.onConfigurationChanged(newConfig);
2961 // Reload the ad for the free flavor if we are not in full screen mode.
2962 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2964 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2966 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2967 adView = findViewById(R.id.adview);
2970 // `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:
2971 // https://code.google.com/p/android/issues/detail?id=20493#c8
2972 // ActivityCompat.invalidateOptionsMenu(this);
2976 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2977 // Store the `HitTestResult`.
2978 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2981 final String imageUrl;
2982 final String linkUrl;
2984 // Get a handle for the `ClipboardManager`.
2985 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2987 // Remove the lint errors below that `clipboardManager` might be `null`.
2988 assert clipboardManager != null;
2990 switch (hitTestResult.getType()) {
2991 // `SRC_ANCHOR_TYPE` is a link.
2992 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2993 // Get the target URL.
2994 linkUrl = hitTestResult.getExtra();
2996 // Set the target URL as the title of the `ContextMenu`.
2997 menu.setHeaderTitle(linkUrl);
2999 // Add a `Load URL` entry.
3000 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
3005 // Add a `Copy URL` entry.
3006 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3007 // Save the link URL in a `ClipData`.
3008 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
3010 // Set the `ClipData` as the clipboard's primary clip.
3011 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
3015 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3016 menu.add(R.string.cancel);
3019 case WebView.HitTestResult.EMAIL_TYPE:
3020 // Get the target URL.
3021 linkUrl = hitTestResult.getExtra();
3023 // Set the target URL as the title of the `ContextMenu`.
3024 menu.setHeaderTitle(linkUrl);
3026 // Add a `Write Email` entry.
3027 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
3028 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
3029 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
3031 // Parse the url and set it as the data for the `Intent`.
3032 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
3034 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
3035 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3038 startActivity(emailIntent);
3042 // Add a `Copy Email Address` entry.
3043 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
3044 // Save the email address in a `ClipData`.
3045 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
3047 // Set the `ClipData` as the clipboard's primary clip.
3048 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
3052 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3053 menu.add(R.string.cancel);
3056 // `IMAGE_TYPE` is an image.
3057 case WebView.HitTestResult.IMAGE_TYPE:
3058 // Get the image URL.
3059 imageUrl = hitTestResult.getExtra();
3061 // Set the image URL as the title of the `ContextMenu`.
3062 menu.setHeaderTitle(imageUrl);
3064 // Add a `View Image` entry.
3065 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3070 // Add a `Download Image` entry.
3071 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3072 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
3073 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3074 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3078 // Add a `Copy URL` entry.
3079 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3080 // Save the image URL in a `ClipData`.
3081 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3083 // Set the `ClipData` as the clipboard's primary clip.
3084 clipboardManager.setPrimaryClip(srcImageTypeClipData);
3088 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3089 menu.add(R.string.cancel);
3093 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
3094 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
3095 // Get the image URL.
3096 imageUrl = hitTestResult.getExtra();
3098 // Set the image URL as the title of the `ContextMenu`.
3099 menu.setHeaderTitle(imageUrl);
3101 // Add a `View Image` entry.
3102 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
3107 // Add a `Download Image` entry.
3108 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
3109 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
3110 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
3111 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
3115 // Add a `Copy URL` entry.
3116 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
3117 // Save the image URL in a `ClipData`.
3118 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
3120 // Set the `ClipData` as the clipboard's primary clip.
3121 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
3125 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
3126 menu.add(R.string.cancel);
3132 public void onAddDomain(AppCompatDialogFragment dialogFragment) {
3133 // Reapply the domain settings on returning to `MainWebViewActivity`.
3134 reapplyDomainSettingsOnRestart = true;
3135 currentDomainName = "";
3137 // Get the new domain name `String` from `dialogFragment`.
3138 EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
3139 String domainNameString = domainNameEditText.getText().toString();
3141 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3142 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3143 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3145 // Create the domain and store the database ID in `currentDomainDatabaseId`.
3146 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
3148 // Create an intent to launch the domains activity.
3149 Intent domainsIntent = new Intent(this, DomainsActivity.class);
3151 // Put extra information instructing the domains activity to directly load the current domain.
3152 domainsIntent.putExtra("LoadDomain", newDomainDatabaseId);
3155 startActivity(domainsIntent);
3159 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
3160 // Get the `EditTexts` from the `dialogFragment`.
3161 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
3162 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
3164 // Extract the strings from the `EditTexts`.
3165 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
3166 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
3168 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
3169 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3170 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
3171 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
3173 // Display the new bookmark below the current items in the (0 indexed) list.
3174 int newBookmarkDisplayOrder = bookmarksListView.getCount();
3176 // Create the bookmark.
3177 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
3179 // Update `bookmarksCursor` with the current contents of this folder.
3180 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3182 // Update the `ListView`.
3183 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3185 // Scroll to the new bookmark.
3186 bookmarksListView.setSelection(newBookmarkDisplayOrder);
3190 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
3191 // Get handles for the views in `dialogFragment`.
3192 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
3193 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
3194 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
3196 // Get new folder name string.
3197 String folderNameString = createFolderNameEditText.getText().toString();
3199 // Get the new folder icon `Bitmap`.
3200 Bitmap folderIconBitmap;
3201 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
3202 // Get the default folder icon and convert it to a `Bitmap`.
3203 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3204 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3205 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3206 } else { // Use the `WebView` favorite icon.
3207 folderIconBitmap = favoriteIconBitmap;
3210 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3211 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3212 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3213 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3215 // Move all the bookmarks down one in the display order.
3216 for (int i = 0; i < bookmarksListView.getCount(); i++) {
3217 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
3218 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
3221 // Create the folder, which will be placed at the top of the `ListView`.
3222 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
3224 // Update `bookmarksCursor` with the current contents of this folder.
3225 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3227 // Update the `ListView`.
3228 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3230 // Scroll to the new folder.
3231 bookmarksListView.setSelection(0);
3235 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
3236 // Get the shortcut name.
3237 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
3238 String shortcutNameString = shortcutNameEditText.getText().toString();
3240 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
3241 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
3243 // Setup the shortcut intent.
3244 Intent shortcutIntent = new Intent();
3245 shortcutIntent.setAction(Intent.ACTION_VIEW);
3246 shortcutIntent.setData(Uri.parse(formattedUrlString));
3248 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
3249 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
3251 // Add the required fields to the shortcut info builder.
3252 shortcutInfoBuilder.setIcon(favoriteIcon);
3253 shortcutInfoBuilder.setIntent(shortcutIntent);
3254 shortcutInfoBuilder.setShortLabel(shortcutNameString);
3256 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
3257 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
3261 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
3262 // Download the image if it has an HTTP or HTTPS URI.
3263 if (imageUrl.startsWith("http")) {
3264 // Get a handle for the system `DOWNLOAD_SERVICE`.
3265 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3267 // Parse `imageUrl`.
3268 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
3270 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
3271 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3272 if (firstPartyCookiesEnabled) {
3273 // Get the cookies for `imageUrl`.
3274 String cookies = cookieManager.getCookie(imageUrl);
3276 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3277 downloadRequest.addRequestHeader("Cookie", cookies);
3280 // Get the file name from `dialogFragment`.
3281 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
3282 String imageName = downloadImageNameEditText.getText().toString();
3284 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
3285 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
3286 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
3287 } else { // Only set the title using `imageName`.
3288 downloadRequest.setTitle(imageName);
3291 // Allow `MediaScanner` to index the download if it is a media file.
3292 downloadRequest.allowScanningByMediaScanner();
3294 // Add the URL as the description for the download.
3295 downloadRequest.setDescription(imageUrl);
3297 // Show the download notification after the download is completed.
3298 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3300 // Remove the lint warning below that `downloadManager` might be `null`.
3301 assert downloadManager != null;
3303 // Initiate the download.
3304 downloadManager.enqueue(downloadRequest);
3305 } else { // The image is not an HTTP or HTTPS URI.
3306 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
3311 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
3312 // Download the file if it has an HTTP or HTTPS URI.
3313 if (downloadUrl.startsWith("http")) {
3315 // Get a handle for the system `DOWNLOAD_SERVICE`.
3316 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
3318 // Parse `downloadUrl`.
3319 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
3321 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
3322 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
3323 if (firstPartyCookiesEnabled) {
3324 // Get the cookies for `downloadUrl`.
3325 String cookies = cookieManager.getCookie(downloadUrl);
3327 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
3328 downloadRequest.addRequestHeader("Cookie", cookies);
3331 // Get the file name from `dialogFragment`.
3332 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
3333 String fileName = downloadFileNameEditText.getText().toString();
3335 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
3336 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
3337 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
3338 } else { // Only set the title using `fileName`.
3339 downloadRequest.setTitle(fileName);
3342 // Allow `MediaScanner` to index the download if it is a media file.
3343 downloadRequest.allowScanningByMediaScanner();
3345 // Add the URL as the description for the download.
3346 downloadRequest.setDescription(downloadUrl);
3348 // Show the download notification after the download is completed.
3349 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3351 // Remove the lint warning below that `downloadManager` might be `null`.
3352 assert downloadManager != null;
3354 // Initiate the download.
3355 downloadManager.enqueue(downloadRequest);
3356 } else { // The download is not an HTTP or HTTPS URI.
3357 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
3362 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
3363 // Get handles for the views from `dialogFragment`.
3364 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
3365 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
3366 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
3368 // Store the bookmark strings.
3369 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
3370 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
3372 // Update the bookmark.
3373 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
3374 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
3375 } else { // Update the bookmark using the `WebView` favorite icon.
3376 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
3377 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
3378 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
3379 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
3381 // Update the bookmark and the favorite icon.
3382 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
3385 // Update `bookmarksCursor` with the current contents of this folder.
3386 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3388 // Update the `ListView`.
3389 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3393 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
3394 // Get handles for the views from `dialogFragment`.
3395 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
3396 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
3397 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
3398 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
3400 // Get the new folder name.
3401 String newFolderNameString = editFolderNameEditText.getText().toString();
3403 // Check if the favorite icon has changed.
3404 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
3405 // Update the name in the database.
3406 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
3407 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
3408 // Get the new folder icon `Bitmap`.
3409 Bitmap folderIconBitmap;
3410 if (defaultFolderIconRadioButton.isChecked()) {
3411 // Get the default folder icon and convert it to a `Bitmap`.
3412 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3413 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3414 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3415 } else { // Use the `WebView` favorite icon.
3416 folderIconBitmap = favoriteIconBitmap;
3419 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3420 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3421 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3422 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3424 // Update the folder icon in the database.
3425 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
3426 } else { // The folder icon and the name have changed.
3427 // Get the new folder icon `Bitmap`.
3428 Bitmap folderIconBitmap;
3429 if (defaultFolderIconRadioButton.isChecked()) {
3430 // Get the default folder icon and convert it to a `Bitmap`.
3431 Drawable folderIconDrawable = folderIconImageView.getDrawable();
3432 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
3433 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
3434 } else { // Use the `WebView` favorite icon.
3435 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
3438 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
3439 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
3440 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
3441 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
3443 // Update the folder name and icon in the database.
3444 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
3447 // Update `bookmarksCursor` with the current contents of this folder.
3448 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3450 // Update the `ListView`.
3451 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
3455 public void onHttpAuthenticationCancel() {
3456 // Cancel the `HttpAuthHandler`.
3457 httpAuthHandler.cancel();
3461 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
3462 // Get handles for the `EditTexts`.
3463 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
3464 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
3466 // Proceed with the HTTP authentication.
3467 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
3470 public void viewSslCertificate(View view) {
3471 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
3472 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
3473 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
3477 public void onSslErrorCancel() {
3478 sslErrorHandler.cancel();
3482 public void onSslErrorProceed() {
3483 sslErrorHandler.proceed();
3487 public void onSslMismatchBack() {
3488 if (mainWebView.canGoBack()) { // There is a back page in the history.
3489 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3490 navigatingHistory = true;
3493 mainWebView.goBack();
3494 } else { // There are no pages to go back to.
3495 // Load a blank page
3501 public void onSslMismatchProceed() {
3502 // Do not check the pinned SSL certificate for this domain again until the domain changes.
3503 ignorePinnedSslCertificate = true;
3507 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
3508 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3509 navigatingHistory = true;
3511 // Load the history entry.
3512 mainWebView.goBackOrForward(moveBackOrForwardSteps);
3516 public void onClearHistory() {
3517 // Clear the history.
3518 mainWebView.clearHistory();
3521 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
3523 public void onBackPressed() {
3524 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
3525 // Close the navigation drawer.
3526 drawerLayout.closeDrawer(GravityCompat.START);
3527 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
3528 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
3529 // close the bookmarks drawer.
3530 drawerLayout.closeDrawer(GravityCompat.END);
3531 } else { // A subfolder is displayed.
3532 // Place the former parent folder in `currentFolder`.
3533 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
3535 // Load the new folder.
3536 loadBookmarksFolder();
3539 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
3540 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
3541 navigatingHistory = true;
3544 mainWebView.goBack();
3545 } else { // There isn't anything to do in Privacy Browser.
3546 // Pass `onBackPressed()` to the system.
3547 super.onBackPressed();
3551 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
3552 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
3553 String unformattedUrlString = urlTextBox.getText().toString().trim();
3555 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
3556 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
3557 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
3558 if (!unformattedUrlString.startsWith("http")) {
3559 unformattedUrlString = "http://" + unformattedUrlString;
3562 // Initialize `unformattedUrl`.
3563 URL unformattedUrl = null;
3565 // 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.
3567 unformattedUrl = new URL(unformattedUrlString);
3568 } catch (MalformedURLException e) {
3569 e.printStackTrace();
3572 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
3573 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
3574 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
3575 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
3576 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
3577 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
3580 Uri.Builder formattedUri = new Uri.Builder();
3581 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
3583 // Decode `formattedUri` as a `String` in `UTF-8`.
3584 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
3586 // Sanitize the search input and convert it to a search.
3587 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
3589 // Add the base search URL.
3590 formattedUrlString = searchURL + encodedUrlString;
3593 // Clear the focus from the URL text box. Otherwise, proximate typing in the box will retain the colorized formatting instead of being reset during refocus.
3594 urlTextBox.clearFocus();
3596 loadUrl(formattedUrlString);
3600 private void loadUrl(String url) {
3601 // Apply any custom domain settings.
3602 applyDomainSettings(url);
3605 mainWebView.loadUrl(url, customHeaders);
3607 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
3608 urlIsLoading = true;
3611 public void findPreviousOnPage(View view) {
3612 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
3613 mainWebView.findNext(false);
3616 public void findNextOnPage(View view) {
3617 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
3618 mainWebView.findNext(true);
3621 public void closeFindOnPage(View view) {
3622 // Delete the contents of `find_on_page_edittext`.
3623 findOnPageEditText.setText(null);
3625 // Clear the highlighted phrases.
3626 mainWebView.clearMatches();
3628 // Hide the Find on Page `RelativeLayout`.
3629 findOnPageLinearLayout.setVisibility(View.GONE);
3631 // Show the URL app bar.
3632 supportAppBar.setVisibility(View.VISIBLE);
3634 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
3635 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
3638 private void applyAppSettings() {
3639 // Get a handle for the shared preferences.
3640 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3642 // Store the values from the shared preferences in variables.
3643 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
3644 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
3645 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
3646 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
3647 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
3648 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
3649 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
3650 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
3651 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
3652 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
3653 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
3654 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
3655 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
3656 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
3657 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
3659 // Set the homepage, search, and proxy options.
3660 if (proxyThroughOrbot) { // Set the Tor options.
3661 // Set `torHomepageString` as `homepage`.
3662 homepage = torHomepageString;
3664 // If formattedUrlString is null assign the homepage to it.
3665 if (formattedUrlString == null) {
3666 formattedUrlString = homepage;
3669 // Set the search URL.
3670 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
3671 searchURL = torSearchCustomURLString;
3672 } else { // Use the string from the pre-built list.
3673 searchURL = torSearchString;
3676 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
3677 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
3679 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
3681 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
3683 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
3686 // Display a message to the user if we are waiting on Orbot.
3687 if (!orbotStatus.equals("ON")) {
3688 // Set `waitingForOrbot`.
3689 waitingForOrbot = true;
3691 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
3692 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
3694 } else { // Set the non-Tor options.
3695 // Set `homepageString` as `homepage`.
3696 homepage = homepageString;
3698 // If formattedUrlString is null assign the homepage to it.
3699 if (formattedUrlString == null) {
3700 formattedUrlString = homepage;
3703 // Set the search URL.
3704 if (searchString.equals("Custom URL")) { // Get the custom URL string.
3705 searchURL = searchCustomURLString;
3706 } else { // Use the string from the pre-built list.
3707 searchURL = searchString;
3710 // Reset the proxy to default. The host is `""` and the port is `"0"`.
3711 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
3713 // Set the default `appBar` background. `this` refers to the context.
3715 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
3717 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
3720 // Reset `waitingForOrbot.
3721 waitingForOrbot = false;
3724 // Set swipe to refresh.
3725 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
3727 // Set Do Not Track status.
3728 if (doNotTrackEnabled) {
3729 customHeaders.put("DNT", "1");
3731 customHeaders.remove("DNT");
3734 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
3735 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
3736 if (hideSystemBarsOnFullscreen) { // Hide everything.
3737 // Remove the translucent navigation setting if it is currently flagged.
3738 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3740 // Remove the translucent status bar overlay.
3741 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3743 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
3744 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
3746 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
3747 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
3748 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
3750 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
3751 } else { // Hide everything except the status and navigation bars.
3752 // Add the translucent status flag if it is unset.
3753 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3755 if (translucentNavigationBarOnFullscreen) {
3756 // Set the navigation bar to be translucent.
3757 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3759 // Set the navigation bar to be black.
3760 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3763 } else { // Switch to normal viewing mode.
3764 // Reset `inFullScreenBrowsingMode` to `false`.
3765 inFullScreenBrowsingMode = false;
3767 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
3768 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
3772 // Show the `BannerAd` in the free flavor.
3773 if (BuildConfig.FLAVOR.contentEquals("free")) {
3774 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
3775 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
3777 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3778 adView = findViewById(R.id.adview);
3781 // Remove the translucent navigation bar flag if it is set.
3782 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3784 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3785 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3787 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3788 rootCoordinatorLayout.setSystemUiVisibility(0);
3790 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3791 rootCoordinatorLayout.setFitsSystemWindows(true);
3795 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3796 @SuppressWarnings("deprecation")
3797 private void applyDomainSettings(String url) {
3798 // Reset `navigatingHistory`.
3799 navigatingHistory = false;
3801 // Parse the URL into a URI.
3802 Uri uri = Uri.parse(url);
3804 // Extract the domain from `uri`.
3805 String hostName = uri.getHost();
3807 // Initialize `loadingNewDomainName`.
3808 boolean loadingNewDomainName;
3810 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3811 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3812 //noinspection SimplifiableIfStatement
3813 if ((hostName == null) || (currentDomainName == null)) {
3814 loadingNewDomainName = true;
3815 } else { // Determine if `hostName` equals `currentDomainName`.
3816 loadingNewDomainName = !hostName.equals(currentDomainName);
3819 // 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.
3820 if (loadingNewDomainName) {
3821 // Set the new `hostname` as the `currentDomainName`.
3822 currentDomainName = hostName;
3824 // Reset `ignorePinnedSslCertificate`.
3825 ignorePinnedSslCertificate = false;
3827 // Reset `favoriteIconBitmap` and display it in the `appbar`.
3828 favoriteIconBitmap = favoriteIconDefaultBitmap;
3829 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3831 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3832 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3833 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3835 // Get a full cursor from `domainsDatabaseHelper`.
3836 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3838 // Initialize `domainSettingsSet`.
3839 Set<String> domainSettingsSet = new HashSet<>();
3841 // Get the domain name column index.
3842 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3844 // Populate `domainSettingsSet`.
3845 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3846 // Move `domainsCursor` to the current row.
3847 domainNameCursor.moveToPosition(i);
3849 // Store the domain name in `domainSettingsSet`.
3850 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3853 // Close `domainNameCursor.
3854 domainNameCursor.close();
3856 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3857 domainSettingsApplied = false;
3858 String domainNameInDatabase = null;
3860 // Check the hostname.
3861 if (domainSettingsSet.contains(hostName)) {
3862 domainSettingsApplied = true;
3863 domainNameInDatabase = hostName;
3866 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3867 if (hostName != null) {
3868 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3869 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3870 domainSettingsApplied = true;
3871 domainNameInDatabase = "*." + hostName;
3874 // Strip out the lowest subdomain of `host`.
3875 hostName = hostName.substring(hostName.indexOf(".") + 1);
3879 // Get a handle for the shared preference. `this` references the current context.
3880 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3882 // Store the general preference information.
3883 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3884 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3885 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3886 nightMode = sharedPreferences.getBoolean("night_mode", false);
3888 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3889 // Get a cursor for the current host and move it to the first position.
3890 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3891 currentHostDomainSettingsCursor.moveToFirst();
3893 // Get the settings from the cursor.
3894 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3895 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3896 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3897 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3898 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3899 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3900 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3901 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3902 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3903 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3904 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3905 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3906 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3907 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3908 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3909 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3910 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3912 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3913 switch (nightModeInt) {
3914 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3918 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3923 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3925 javaScriptEnabled = true;
3928 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3929 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3930 pinnedDomainSslStartDate = null;
3932 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3935 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3936 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3937 pinnedDomainSslEndDate = null;
3939 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3942 // Close `currentHostDomainSettingsCursor`.
3943 currentHostDomainSettingsCursor.close();
3945 // Apply the domain settings.
3946 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3947 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3948 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3949 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3951 // Apply the font size.
3952 if (fontSize == 0) { // Apply the default font size.
3953 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3954 } else { // Apply the specified font size.
3955 mainWebView.getSettings().setTextZoom(fontSize);
3958 // Set third-party cookies status if API >= 21.
3959 if (Build.VERSION.SDK_INT >= 21) {
3960 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3963 // 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.
3964 // <https://redmine.stoutner.com/issues/160>
3965 if (!urlIsLoading) {
3966 switch (userAgentString) {
3967 case "System default user agent":
3968 // Set the user agent according to the system default.
3969 switch (defaultUserAgentString) {
3970 case "WebView default user agent":
3971 // Set the user agent to `""`, which uses the default value.
3972 mainWebView.getSettings().setUserAgentString("");
3975 case "Custom user agent":
3976 // Set the custom user agent.
3977 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3981 // Use the selected user agent.
3982 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3986 case "WebView default user agent":
3987 // Set the user agent to `""`, which uses the default value.
3988 mainWebView.getSettings().setUserAgentString("");
3992 // Use the selected user agent.
3993 mainWebView.getSettings().setUserAgentString(userAgentString);
3996 // Store the applied user agent string.
3997 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4000 // 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.
4002 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
4004 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
4006 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
4007 // Store the values from `sharedPreferences` in variables.
4008 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
4009 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
4010 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
4011 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
4012 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
4014 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
4016 javaScriptEnabled = true;
4019 // Apply the default settings.
4020 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
4021 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
4022 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
4023 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
4024 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
4026 // Reset the pinned SSL certificate information.
4027 domainSettingsDatabaseId = -1;
4028 pinnedDomainSslCertificate = false;
4029 pinnedDomainSslIssuedToCNameString = "";
4030 pinnedDomainSslIssuedToONameString = "";
4031 pinnedDomainSslIssuedToUNameString = "";
4032 pinnedDomainSslIssuedByCNameString = "";
4033 pinnedDomainSslIssuedByONameString = "";
4034 pinnedDomainSslIssuedByUNameString = "";
4035 pinnedDomainSslStartDate = null;
4036 pinnedDomainSslEndDate = null;
4038 // Set third-party cookies status if API >= 21.
4039 if (Build.VERSION.SDK_INT >= 21) {
4040 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
4043 // 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.
4044 // <https://redmine.stoutner.com/issues/160>
4045 if (!urlIsLoading) {
4046 switch (defaultUserAgentString) {
4047 case "WebView default user agent":
4048 // Set the user agent to `""`, which uses the default value.
4049 mainWebView.getSettings().setUserAgentString("");
4052 case "Custom user agent":
4053 // Set the custom user agent.
4054 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
4058 // Use the selected user agent.
4059 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
4062 // Store the applied user agent string.
4063 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
4066 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
4067 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
4070 // Close `domainsDatabaseHelper`.
4071 domainsDatabaseHelper.close();
4073 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
4074 onTheFlyDisplayImagesSet = false;
4075 setDisplayWebpageImages();
4077 // Update the privacy icons, but only if `mainMenu` has already been populated.
4078 if (mainMenu != null) {
4079 updatePrivacyIcons(true);
4084 private void setDisplayWebpageImages() {
4085 if (!onTheFlyDisplayImagesSet) {
4086 if (domainSettingsApplied) { // Custom domain settings are applied.
4087 switch (displayWebpageImagesInt) {
4088 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
4089 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4092 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
4093 mainWebView.getSettings().setLoadsImagesAutomatically(true);
4096 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
4097 mainWebView.getSettings().setLoadsImagesAutomatically(false);
4100 } else { // Default settings are applied.
4101 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
4106 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
4107 // Get handles for the icons.
4108 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
4109 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
4110 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
4111 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
4113 // Update `privacyIcon`.
4114 if (javaScriptEnabled) { // JavaScript is enabled.
4115 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
4116 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
4117 privacyIconMenuItem.setIcon(R.drawable.warning);
4118 } else { // All the dangerous features are disabled.
4119 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
4122 // Update `firstPartyCookiesIcon`.
4123 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
4124 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
4125 } else { // First-party cookies are disabled.
4127 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
4129 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
4133 // Update `domStorageIcon`.
4134 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
4135 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
4136 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
4138 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
4140 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
4142 } else { // JavaScript is disabled, so DOM storage is ghosted.
4144 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
4146 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
4150 // Update `formDataIcon`.
4151 if (saveFormDataEnabled) { // Form data is enabled.
4152 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
4153 } else { // Form data is disabled.
4155 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
4157 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
4161 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
4162 if (runInvalidateOptionsMenu) {
4163 invalidateOptionsMenu();
4167 private void highlightUrlText() {
4168 String urlString = urlTextBox.getText().toString();
4170 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
4171 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4172 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
4173 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4176 // Get the index of the `/` immediately after the domain name.
4177 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
4179 // De-emphasize the text after the domain name.
4180 if (endOfDomainName > 0) {
4181 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
4185 private void loadBookmarksFolder() {
4186 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
4187 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
4189 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
4190 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
4192 public View newView(Context context, Cursor cursor, ViewGroup parent) {
4193 // Inflate the individual item layout. `false` does not attach it to the root.
4194 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
4198 public void bindView(View view, Context context, Cursor cursor) {
4199 // Get handles for the views.
4200 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
4201 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
4203 // Get the favorite icon byte array from the `Cursor`.
4204 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
4206 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
4207 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
4209 // Display the bitmap in `bookmarkFavoriteIcon`.
4210 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
4212 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
4213 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
4214 bookmarkNameTextView.setText(bookmarkNameString);
4216 // Make the font bold for folders.
4217 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
4218 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
4219 } else { // Reset the font to default for normal bookmarks.
4220 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
4225 // Populate the `ListView` with the adapter.
4226 bookmarksListView.setAdapter(bookmarksCursorAdapter);
4228 // Set the bookmarks drawer title.
4229 if (currentBookmarksFolder.isEmpty()) {
4230 bookmarksTitleTextView.setText(R.string.bookmarks);
4232 bookmarksTitleTextView.setText(currentBookmarksFolder);