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.Patterns;
73 import android.view.ContextMenu;
74 import android.view.GestureDetector;
75 import android.view.KeyEvent;
76 import android.view.Menu;
77 import android.view.MenuItem;
78 import android.view.MotionEvent;
79 import android.view.View;
80 import android.view.ViewGroup;
81 import android.view.WindowManager;
82 import android.view.inputmethod.InputMethodManager;
83 import android.webkit.CookieManager;
84 import android.webkit.HttpAuthHandler;
85 import android.webkit.SslErrorHandler;
86 import android.webkit.WebBackForwardList;
87 import android.webkit.WebChromeClient;
88 import android.webkit.WebResourceResponse;
89 import android.webkit.WebStorage;
90 import android.webkit.WebView;
91 import android.webkit.WebViewClient;
92 import android.webkit.WebViewDatabase;
93 import android.widget.CursorAdapter;
94 import android.widget.EditText;
95 import android.widget.FrameLayout;
96 import android.widget.ImageView;
97 import android.widget.LinearLayout;
98 import android.widget.ListView;
99 import android.widget.ProgressBar;
100 import android.widget.RadioButton;
101 import android.widget.RelativeLayout;
102 import android.widget.TextView;
104 import com.stoutner.privacybrowser.BannerAd;
105 import com.stoutner.privacybrowser.BuildConfig;
106 import com.stoutner.privacybrowser.R;
107 import com.stoutner.privacybrowser.dialogs.AddDomainDialog;
108 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
109 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
110 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
111 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
112 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
113 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
114 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
115 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
116 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
117 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
118 import com.stoutner.privacybrowser.helpers.BlockListHelper;
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.ByteArrayInputStream;
126 import java.io.ByteArrayOutputStream;
128 import java.io.IOException;
129 import java.io.UnsupportedEncodingException;
130 import java.net.MalformedURLException;
132 import java.net.URLDecoder;
133 import java.net.URLEncoder;
134 import java.util.ArrayList;
135 import java.util.Date;
136 import java.util.HashMap;
137 import java.util.HashSet;
138 import java.util.List;
139 import java.util.Map;
140 import java.util.Set;
142 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
143 public class MainWebViewActivity extends AppCompatActivity implements AddDomainDialog.AddDomainListener, CreateBookmarkDialog.CreateBookmarkListener,
144 CreateBookmarkFolderDialog.CreateBookmarkFolderListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener, DownloadFileDialog.DownloadFileListener,
145 DownloadImageDialog.DownloadImageListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener,
146 NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener,
147 UrlHistoryDialog.UrlHistoryListener {
149 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`,
150 // `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
151 // `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`,
152 // and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
153 public static boolean darkTheme;
155 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`,
156 // `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`,
157 // `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
158 public static Bitmap favoriteIconBitmap;
160 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
161 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
162 public static String formattedUrlString;
164 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`,
165 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
166 public static SslCertificate sslCertificate;
168 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
169 public static String orbotStatus;
171 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
172 public static String webViewTitle;
174 // `appliedUserAgentString` is public static so it can be accessed from `ViewSourceActivity`. It is also used in `applyDomainSettings()`.
175 public static String appliedUserAgentString;
177 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
178 public static boolean reloadOnRestart;
180 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
181 public static boolean loadUrlOnRestart;
183 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
184 public static boolean restartFromBookmarksActivity;
186 // The block list versions are public static so they can be accessed from `AboutTabFragment`. They are also used in `onCreate()`.
187 public static String easyListVersion;
188 public static String easyPrivacyVersion;
189 public static String fanboyAnnoyanceVersion;
190 public static String fanboySocialVersion;
192 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`,
193 // `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
194 public static String currentBookmarksFolder;
196 // `domainSettingsDatabaseId` is public static so it can be accessed from `PinnedSslCertificateMismatchDialog`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
197 public static int domainSettingsDatabaseId;
199 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
200 public static String pinnedDomainSslIssuedToCNameString;
201 public static String pinnedDomainSslIssuedToONameString;
202 public static String pinnedDomainSslIssuedToUNameString;
203 public static String pinnedDomainSslIssuedByCNameString;
204 public static String pinnedDomainSslIssuedByONameString;
205 public static String pinnedDomainSslIssuedByUNameString;
206 public static Date pinnedDomainSslStartDate;
207 public static Date pinnedDomainSslEndDate;
210 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
211 private ActionBar appBar;
213 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
214 private boolean navigatingHistory;
216 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
217 private Bitmap favoriteIconDefaultBitmap;
219 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
220 private DrawerLayout drawerLayout;
222 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
223 private CoordinatorLayout rootCoordinatorLayout;
225 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`,
226 // `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`, `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
227 private WebView mainWebView;
229 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
230 private FrameLayout fullScreenVideoFrameLayout;
232 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
233 private SwipeRefreshLayout swipeRefreshLayout;
235 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
236 private RelativeLayout urlAppBarRelativeLayout;
238 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
239 private ImageView favoriteIconImageView;
241 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
242 private CookieManager cookieManager;
244 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
245 private final Map<String, String> customHeaders = new HashMap<>();
247 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
248 private boolean javaScriptEnabled;
250 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
251 private boolean firstPartyCookiesEnabled;
253 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
254 private boolean thirdPartyCookiesEnabled;
256 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
257 private boolean domStorageEnabled;
259 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
260 private boolean saveFormDataEnabled;
262 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
263 private boolean nightMode;
265 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
266 private boolean swipeToRefreshEnabled;
268 // `displayWebpageImagesBoolean` is used in `applyAppSettings()` and `applyDomainSettings()`.
269 private boolean displayWebpageImagesBoolean;
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 // The block list variables are used in `onCreate()` and `applyAppSettings()`.
278 private boolean easyListEnabled;
279 private boolean easyPrivacyEnabled;
280 private boolean fanboyAnnoyanceListEnabled;
281 private boolean fanboySocialBlockingListEnabled;
283 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
284 private Runtime privacyBrowserRuntime;
286 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
287 private boolean incognitoModeEnabled;
289 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
290 private boolean fullScreenBrowsingModeEnabled;
292 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
293 private boolean inFullScreenBrowsingMode;
295 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
296 private boolean hideSystemBarsOnFullscreen;
298 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
299 private boolean translucentNavigationBarOnFullscreen;
301 // `reapplyDomainSettingsOnRestart` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, and `onAddDomain()`, .
302 private boolean reapplyDomainSettingsOnRestart;
304 // `currentDomainName` is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onAddDomain()`, and `applyDomainSettings()`.
305 private String currentDomainName;
307 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
308 private boolean ignorePinnedSslCertificate;
310 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
311 private boolean waitingForOrbot;
313 // `domainSettingsApplied` is used in `prepareOptionsMenu()`, `applyDomainSettings()`, and `setDisplayWebpageImages()`.
314 private boolean domainSettingsApplied;
316 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
317 private int displayWebpageImagesInt;
319 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
320 private boolean onTheFlyDisplayImagesSet;
322 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
323 private String waitingForOrbotHTMLString;
325 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
326 private String privateDataDirectoryString;
328 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
329 private LinearLayout findOnPageLinearLayout;
331 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
332 private EditText findOnPageEditText;
334 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
335 private Menu mainMenu;
337 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
338 private ActionBarDrawerToggle drawerToggle;
340 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
341 private Toolbar supportAppBar;
343 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
344 private EditText urlTextBox;
346 // The color spans are used in `onCreate()` and `highlightUrlText()`.
347 private ForegroundColorSpan redColorSpan;
348 private ForegroundColorSpan initialGrayColorSpan;
349 private ForegroundColorSpan finalGrayColorSpan;
351 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
354 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
355 private SslErrorHandler sslErrorHandler;
357 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
358 private static HttpAuthHandler httpAuthHandler;
360 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
361 private InputMethodManager inputMethodManager;
363 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
364 private RelativeLayout mainWebViewRelativeLayout;
366 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
367 private boolean urlIsLoading;
369 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
370 private boolean pinnedDomainSslCertificate;
372 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
373 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
375 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
376 private ListView bookmarksListView;
378 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
379 private TextView bookmarksTitleTextView;
381 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
382 private Cursor bookmarksCursor;
384 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
385 private CursorAdapter bookmarksCursorAdapter;
387 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
388 private String oldFolderNameString;
391 // 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.
392 @SuppressLint({"SetJavaScriptEnabled"})
393 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
394 @SuppressWarnings("deprecation")
395 protected void onCreate(Bundle savedInstanceState) {
396 // Get a handle for `sharedPreferences`. `this` references the current context.
397 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
399 // Get the theme preference.
400 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
402 // Set the activity theme.
404 setTheme(R.style.PrivacyBrowserDark);
406 setTheme(R.style.PrivacyBrowserLight);
409 // Run the default commands.
410 super.onCreate(savedInstanceState);
412 // Set the content view.
413 setContentView(R.layout.main_drawerlayout);
415 // Get a handle for `inputMethodManager`.
416 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
418 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
419 supportAppBar = findViewById(R.id.app_bar);
420 setSupportActionBar(supportAppBar);
421 appBar = getSupportActionBar();
423 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
424 assert appBar != null;
426 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
427 appBar.setCustomView(R.layout.url_app_bar);
428 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
430 // Initialize the foreground color spans for highlighting the URLs. We have to use the deprecated `getColor()` until API >= 23.
431 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
432 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
433 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
435 // Get a handle for `urlTextBox`.
436 urlTextBox = findViewById(R.id.url_edittext);
438 // Remove the formatting from `urlTextBar` when the user is editing the text.
439 urlTextBox.setOnFocusChangeListener((View v, boolean hasFocus) -> {
440 if (hasFocus) { // The user is editing `urlTextBox`.
441 // Remove the highlighting.
442 urlTextBox.getText().removeSpan(redColorSpan);
443 urlTextBox.getText().removeSpan(initialGrayColorSpan);
444 urlTextBox.getText().removeSpan(finalGrayColorSpan);
445 } else { // The user has stopped editing `urlTextBox`.
446 // Reapply the highlighting.
451 // Set the go button on the keyboard to load the URL in `urlTextBox`.
452 urlTextBox.setOnKeyListener((View v, int keyCode, KeyEvent event) -> {
453 // If the event is a key-down event on the `enter` button, load the URL.
454 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
455 // Load the URL into the mainWebView and consume the event.
457 loadUrlFromTextBox();
458 } catch (UnsupportedEncodingException e) {
461 // If the enter key was pressed, consume the event.
464 // If any other key was pressed, do not consume the event.
469 // Set `waitingForOrbotHTMLString`.
470 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
472 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
473 currentDomainName = "";
474 orbotStatus = "unknown";
475 waitingForOrbot = false;
477 // Create an Orbot status `BroadcastReceiver`.
478 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
480 public void onReceive(Context context, Intent intent) {
481 // Store the content of the status message in `orbotStatus`.
482 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
484 // If we are waiting on Orbot, load the website now that Orbot is connected.
485 if (orbotStatus.equals("ON") && waitingForOrbot) {
486 // Reset `waitingForOrbot`.
487 waitingForOrbot = false;
489 // Load `formattedUrlString
490 loadUrl(formattedUrlString);
495 // Register `orbotStatusBroadcastReceiver` on `this` context.
496 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
498 // Get handles for views that need to be accessed.
499 drawerLayout = findViewById(R.id.drawerlayout);
500 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
501 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
502 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
503 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
504 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
505 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
506 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
507 mainWebView = findViewById(R.id.main_webview);
508 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
509 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
510 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
511 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
512 favoriteIconImageView = findViewById(R.id.favorite_icon);
514 // 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.
516 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
517 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
518 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
519 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
521 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
522 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
523 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
524 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
527 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
528 launchBookmarksActivityFab.setOnClickListener(v -> {
529 // Create an intent to launch the bookmarks activity.
530 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
532 // Include the current folder with the `Intent`.
533 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
536 startActivity(bookmarksIntent);
539 // Set the create new bookmark folder FAB to display the `AlertDialog`.
540 createBookmarkFolderFab.setOnClickListener(v -> {
541 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
542 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
543 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
546 // Set the create new bookmark FAB to display the `AlertDialog`.
547 createBookmarkFab.setOnClickListener(view -> {
548 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
549 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
550 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
553 // Create a double-tap listener to toggle full-screen mode.
554 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
555 // Override `onDoubleTap()`. All other events are handled using the default settings.
557 public boolean onDoubleTap(MotionEvent event) {
558 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
559 // Toggle `inFullScreenBrowsingMode`.
560 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
562 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
563 // Hide the `appBar`.
566 // Hide the `BannerAd` in the free flavor.
567 if (BuildConfig.FLAVOR.contentEquals("free")) {
568 BannerAd.hideAd(adView);
571 // Modify the system bars.
572 if (hideSystemBarsOnFullscreen) { // Hide everything.
573 // Remove the translucent overlays.
574 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
576 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
577 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
579 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
580 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
581 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
583 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
585 // Set `rootCoordinatorLayout` to fill the whole screen.
586 rootCoordinatorLayout.setFitsSystemWindows(false);
587 } else { // Hide everything except the status and navigation bars.
588 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
589 rootCoordinatorLayout.setFitsSystemWindows(false);
591 // 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.
592 if (translucentNavigationBarOnFullscreen) {
593 // Set the navigation bar to be translucent.
594 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
597 } else { // Switch to normal viewing mode.
598 // Show the `appBar`.
601 // Show the `BannerAd` in the free flavor.
602 if (BuildConfig.FLAVOR.contentEquals("free")) {
603 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
604 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
606 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
607 adView = findViewById(R.id.adview);
610 // Remove the translucent navigation bar flag if it is set.
611 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
613 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
614 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
616 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
617 rootCoordinatorLayout.setSystemUiVisibility(0);
619 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
620 rootCoordinatorLayout.setFitsSystemWindows(true);
623 // Consume the double-tap.
625 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
631 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
632 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
633 // Call `performClick()` on the view, which is required for accessibility.
636 // Send the `event` to `gestureDetector`.
637 return gestureDetector.onTouchEvent(event);
640 // Update `findOnPageCountTextView`.
641 mainWebView.setFindListener(new WebView.FindListener() {
642 // Get a handle for `findOnPageCountTextView`.
643 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
646 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
647 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
648 // Set `findOnPageCountTextView` to `0/0`.
649 findOnPageCountTextView.setText(R.string.zero_of_zero);
650 } else if (isDoneCounting) { // There are matches.
651 // `activeMatchOrdinal` is zero-based.
652 int activeMatch = activeMatchOrdinal + 1;
654 // Build the match string.
655 String matchString = activeMatch + "/" + numberOfMatches;
657 // Set `findOnPageCountTextView`.
658 findOnPageCountTextView.setText(matchString);
663 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
664 findOnPageEditText.addTextChangedListener(new TextWatcher() {
666 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
671 public void onTextChanged(CharSequence s, int start, int before, int count) {
676 public void afterTextChanged(Editable s) {
677 // Search for the text in `mainWebView`.
678 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
682 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
683 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
684 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
685 // Hide the soft keyboard. `0` indicates no additional flags.
686 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
688 // Consume the event.
690 } else { // A different key was pressed.
691 // Do not consume the event.
696 // Implement swipe to refresh
697 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
698 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
699 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
701 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
702 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
703 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
705 // Listen for touches on the navigation menu.
706 final NavigationView navigationView = findViewById(R.id.navigationview);
707 navigationView.setNavigationItemSelectedListener(this);
709 // 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.
710 final Menu navigationMenu = navigationView.getMenu();
711 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
712 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
713 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
715 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
716 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
717 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
719 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
720 currentBookmarksFolder = "";
722 // Load the home folder, which is `""` in the database.
723 loadBookmarksFolder();
725 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
726 // Convert the id from long to int to match the format of the bookmarks database.
727 int databaseID = (int) id;
729 // Get the bookmark `Cursor` for this ID and move it to the first row.
730 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
731 bookmarkCursor.moveToFirst();
733 // Act upon the bookmark according to the type.
734 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
735 // Store the new folder name in `currentBookmarksFolder`.
736 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
738 // Load the new folder.
739 loadBookmarksFolder();
740 } else { // The selected bookmark is not a folder.
741 // Load the bookmark URL.
742 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
744 // Close the bookmarks drawer.
745 drawerLayout.closeDrawer(GravityCompat.END);
748 // Close the `Cursor`.
749 bookmarkCursor.close();
752 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
753 // Convert the database ID from `long` to `int`.
754 int databaseId = (int) id;
756 // Find out if the selected bookmark is a folder.
757 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
760 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
761 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
763 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
764 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
765 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
767 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
768 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
769 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
772 // Consume the event.
776 // The `DrawerListener` allows us to update the Navigation Menu.
777 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
779 public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
783 public void onDrawerOpened(@NonNull View drawerView) {
787 public void onDrawerClosed(@NonNull View drawerView) {
791 public void onDrawerStateChanged(int newState) {
792 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
793 // Update the `Back`, `Forward`, and `History` menu items.
794 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
795 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
796 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
798 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
799 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
801 // Clear the focus from `urlTextBox` if it has it.
802 urlTextBox.clearFocus();
807 // drawerToggle creates the hamburger icon at the start of the AppBar.
808 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
810 // Instantiate the block list helper.
811 BlockListHelper blockListHelper = new BlockListHelper();
813 // Parse the block lists.
814 final ArrayList<List<String[]>> easyList = blockListHelper.parseBlockList(getAssets(), "blocklists/easylist.txt");
815 final ArrayList<List<String[]>> easyPrivacy = blockListHelper.parseBlockList(getAssets(), "blocklists/easyprivacy.txt");
816 final ArrayList<List<String[]>> fanboyAnnoyance = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-annoyance.txt");
817 final ArrayList<List<String[]>> fanboySocial = blockListHelper.parseBlockList(getAssets(), "blocklists/fanboy-social.txt");
819 // Store the list versions.
820 easyListVersion = easyList.get(0).get(0)[0];
821 easyPrivacyVersion = easyPrivacy.get(0).get(0)[0];
822 fanboyAnnoyanceVersion = fanboyAnnoyance.get(0).get(0)[0];
823 fanboySocialVersion = fanboySocial.get(0).get(0)[0];
825 mainWebView.setWebViewClient(new WebViewClient() {
826 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
827 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
828 @SuppressWarnings("deprecation")
830 public boolean shouldOverrideUrlLoading(WebView view, String url) {
831 if (url.startsWith("mailto:")) { // Load the email address in an external email program.
832 // Use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
833 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
835 // Parse the url and set it as the data for the `Intent`.
836 emailIntent.setData(Uri.parse(url));
838 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
839 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
842 startActivity(emailIntent);
844 // Returning `true` indicates the application is handling the URL.
846 } else if (url.startsWith("tel:")) { // Load the phone number in the dialer.
847 // `ACTION_DIAL` open the dialer and loads the phone number, but waits for the user to place the call.
848 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
850 // Add the phone number to the intent.
851 dialIntent.setData(Uri.parse(url));
853 // `FLAG_ACTIVITY_NEW_TASK` opens the dialer in a new task instead as part of Privacy Browser.
854 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
857 startActivity(dialIntent);
859 // Returning `true` indicates the application is handling the URL.
861 } else { // Load the URL in Privacy Browser.
862 // Apply the domain settings for the new URL.
863 applyDomainSettings(url);
865 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
870 // Check requests against the block lists. The deprecated `shouldInterceptRequest` must be used until minimum API >= 21.
871 @SuppressWarnings("deprecation")
873 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
874 // Create an empty web resource response to be used if the resource request is blocked.
875 WebResourceResponse emptyWebResourceResponse = new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
877 // Check EasyList if it is enabled.
878 if (easyListEnabled) {
879 if (blockListHelper.isBlocked(formattedUrlString, url, easyList)) {
880 // The resource request was blocked. Return an empty web resource response.
881 return emptyWebResourceResponse;
885 // Check EasyPrivacy if it is enabled.
886 if (easyPrivacyEnabled) {
887 if (blockListHelper.isBlocked(formattedUrlString, url, easyPrivacy)) {
888 // The resource request was blocked. Return an empty web resource response.
889 return emptyWebResourceResponse;
893 // Check Fanboy’s Annoyance List if it is enabled.
894 if (fanboyAnnoyanceListEnabled) {
895 if (blockListHelper.isBlocked(formattedUrlString, url, fanboyAnnoyance)) {
896 // The resource request was blocked. Return an empty web resource response.
897 return emptyWebResourceResponse;
899 } else if (fanboySocialBlockingListEnabled){ // Only check Fanboy’s Social Blocking List if Fanboy’s Annoyance List is disabled.
900 if (blockListHelper.isBlocked(formattedUrlString, url, fanboySocial)) {
901 // The resource request was blocked. Return an empty web resource response.
902 return emptyWebResourceResponse;
906 // The resource request has not been blocked. `return null` loads the requested resource.
910 // Handle HTTP authentication requests.
912 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
913 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
914 httpAuthHandler = handler;
916 // Display the HTTP authentication dialog.
917 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
918 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
921 // Update the URL in urlTextBox when the page starts to load.
923 public void onPageStarted(WebView view, String url, Bitmap favicon) {
924 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
926 mainWebView.setVisibility(View.INVISIBLE);
929 // Hide the keyboard. `0` indicates no additional flags.
930 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
932 // Check to see if we are waiting on Orbot.
933 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
934 // 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.
935 formattedUrlString = url;
937 // Display the formatted URL text.
938 urlTextBox.setText(formattedUrlString);
940 // Apply text highlighting to `urlTextBox`.
943 // Apply any custom domain settings if the URL was loaded by navigating history.
944 if (navigatingHistory) {
945 applyDomainSettings(url);
948 // 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.
953 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
955 public void onPageFinished(WebView view, String url) {
956 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
957 urlIsLoading = false;
959 // Clear the cache and history if Incognito Mode is enabled.
960 if (incognitoModeEnabled) {
961 // Clear the cache. `true` includes disk files.
962 mainWebView.clearCache(true);
964 // Clear the back/forward history.
965 mainWebView.clearHistory();
967 // Manually delete cache folders.
969 // Delete the main `cache` folder.
970 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
972 // 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`.
973 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
974 } catch (IOException e) {
975 // Do nothing if an error is thrown.
979 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
980 if (!waitingForOrbot) {
981 // Check to see if `WebView` has set `url` to be `about:blank`.
982 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
983 // Set `formattedUrlString` to `""`.
984 formattedUrlString = "";
986 urlTextBox.setText(formattedUrlString);
988 // Request focus for `urlTextBox`.
989 urlTextBox.requestFocus();
991 // Display the keyboard.
992 inputMethodManager.showSoftInput(urlTextBox, 0);
994 // Apply the domain settings. This clears any settings from the previous domain.
995 applyDomainSettings(formattedUrlString);
996 } else { // `WebView` has loaded a webpage.
997 // Set `formattedUrlString`.
998 formattedUrlString = url;
1000 // Only update `urlTextBox` if the user is not typing in it.
1001 if (!urlTextBox.hasFocus()) {
1002 // Display the formatted URL text.
1003 urlTextBox.setText(formattedUrlString);
1005 // Apply text highlighting to `urlTextBox`.
1010 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1011 sslCertificate = mainWebView.getCertificate();
1013 // 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.
1014 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1015 // Initialize the current SSL certificate variables.
1016 String currentWebsiteIssuedToCName = "";
1017 String currentWebsiteIssuedToOName = "";
1018 String currentWebsiteIssuedToUName = "";
1019 String currentWebsiteIssuedByCName = "";
1020 String currentWebsiteIssuedByOName = "";
1021 String currentWebsiteIssuedByUName = "";
1022 Date currentWebsiteSslStartDate = null;
1023 Date currentWebsiteSslEndDate = null;
1026 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1027 if (sslCertificate != null) {
1028 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1029 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1030 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1031 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1032 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1033 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1034 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1035 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1038 // 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`.
1039 String currentWebsiteSslStartDateString = "";
1040 String currentWebsiteSslEndDateString = "";
1041 String pinnedDomainSslStartDateString = "";
1042 String pinnedDomainSslEndDateString = "";
1044 // Convert the `Dates` to `Strings` if they are not `null`.
1045 if (currentWebsiteSslStartDate != null) {
1046 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1049 if (currentWebsiteSslEndDate != null) {
1050 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1053 if (pinnedDomainSslStartDate != null) {
1054 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1057 if (pinnedDomainSslEndDate != null) {
1058 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1061 // Check to see if the pinned SSL certificate matches the current website certificate.
1062 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) ||
1063 !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) || !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) ||
1064 !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1065 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) {
1066 // The pinned SSL certificate doesn't match the current domain certificate.
1067 //Display the pinned SSL certificate mismatch `AlertDialog`.
1068 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1069 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1075 // Handle SSL Certificate errors.
1077 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1078 // Get the current website SSL certificate.
1079 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1081 // Extract the individual pieces of information from the current website SSL certificate.
1082 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1083 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1084 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1085 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1086 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1087 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1088 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1089 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1091 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1092 if (pinnedDomainSslCertificate &&
1093 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) &&
1094 currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) && currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) &&
1095 currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1096 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) {
1097 // An SSL certificate is pinned and matches the current domain certificate.
1098 // Proceed to the website without displaying an error.
1100 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1101 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1102 sslErrorHandler = handler;
1104 // Display the SSL error `AlertDialog`.
1105 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1106 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1111 // Get a handle for the progress bar.
1112 final ProgressBar progressBar = findViewById(R.id.progress_bar);
1114 mainWebView.setWebChromeClient(new WebChromeClient() {
1115 // Update the progress bar when a page is loading.
1117 public void onProgressChanged(WebView view, int progress) {
1118 // Inject the night mode CSS if night mode is enabled.
1120 // `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
1121 // used by WordPress. `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color.
1122 // `border: none` removes all borders, which can also be used to underline text.
1123 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
1124 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; " +
1125 "style.innerHTML = '* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important;" +
1126 "text-shadow: none !important; border: none !important;} a {color: #1565C0 !important;}'; parent.appendChild(style)})()", value -> {
1127 // Initialize a `Handler` to display `mainWebView`.
1128 Handler displayWebViewHandler = new Handler();
1130 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
1131 Runnable displayWebViewRunnable = () -> {
1132 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
1133 if (progressBar.getVisibility() == View.GONE) {
1134 mainWebView.setVisibility(View.VISIBLE);
1138 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
1139 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
1143 // Update the progress bar.
1144 progressBar.setProgress(progress);
1146 // Set the visibility of the progress bar.
1147 if (progress < 100) {
1148 // Show the progress bar.
1149 progressBar.setVisibility(View.VISIBLE);
1151 // Hide the progress bar.
1152 progressBar.setVisibility(View.GONE);
1154 // Display `mainWebView` if night mode is disabled.
1155 // 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
1156 // currently enabled.
1158 mainWebView.setVisibility(View.VISIBLE);
1161 //Stop the `SwipeToRefresh` indicator if it is running
1162 swipeRefreshLayout.setRefreshing(false);
1166 // Set the favorite icon when it changes.
1168 public void onReceivedIcon(WebView view, Bitmap icon) {
1169 // Only update the favorite icon if the website has finished loading.
1170 if (progressBar.getVisibility() == View.GONE) {
1171 // Save a copy of the favorite icon.
1172 favoriteIconBitmap = icon;
1174 // Place the favorite icon in the appBar.
1175 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1179 // Save a copy of the title when it changes.
1181 public void onReceivedTitle(WebView view, String title) {
1182 // Save a copy of the title.
1183 webViewTitle = title;
1186 // Enter full screen video
1188 public void onShowCustomView(View view, CustomViewCallback callback) {
1189 // Pause the ad if this is the free flavor.
1190 if (BuildConfig.FLAVOR.contentEquals("free")) {
1191 BannerAd.pauseAd(adView);
1194 // Remove the translucent overlays.
1195 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1197 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1198 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1200 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1201 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1202 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
1204 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1206 // Set `rootCoordinatorLayout` to fill the entire screen.
1207 rootCoordinatorLayout.setFitsSystemWindows(false);
1209 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1210 fullScreenVideoFrameLayout.addView(view);
1211 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1214 // Exit full screen video
1215 public void onHideCustomView() {
1216 // Hide `fullScreenVideoFrameLayout`.
1217 fullScreenVideoFrameLayout.removeAllViews();
1218 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1220 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1221 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1223 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1224 rootCoordinatorLayout.setFitsSystemWindows(true);
1226 // Show the ad if this is the free flavor.
1227 if (BuildConfig.FLAVOR.contentEquals("free")) {
1228 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1229 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1231 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1232 adView = findViewById(R.id.adview);
1237 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1238 registerForContextMenu(mainWebView);
1240 // Allow the downloading of files.
1241 mainWebView.setDownloadListener((String url, String userAgent, String contentDisposition, String mimetype, long contentLength) -> {
1242 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1243 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1244 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1247 // Allow pinch to zoom.
1248 mainWebView.getSettings().setBuiltInZoomControls(true);
1250 // Hide zoom controls.
1251 mainWebView.getSettings().setDisplayZoomControls(false);
1253 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1254 mainWebView.getSettings().setUseWideViewPort(true);
1256 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1257 mainWebView.getSettings().setLoadWithOverviewMode(true);
1259 // Explicitly disable geolocation.
1260 mainWebView.getSettings().setGeolocationEnabled(false);
1262 // Initialize cookieManager.
1263 cookieManager = CookieManager.getInstance();
1265 // 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).
1266 customHeaders.put("X-Requested-With", "");
1268 // 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.
1269 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1271 // Get the intent that started the app.
1272 final Intent launchingIntent = getIntent();
1274 // Extract the launching intent data as `launchingIntentUriData`.
1275 final Uri launchingIntentUriData = launchingIntent.getData();
1277 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1278 if (launchingIntentUriData != null) {
1279 formattedUrlString = launchingIntentUriData.toString();
1282 // Get a handle for the `Runtime`.
1283 privacyBrowserRuntime = Runtime.getRuntime();
1285 // Store the application's private data directory.
1286 privateDataDirectoryString = getApplicationInfo().dataDir;
1287 // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1289 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1290 inFullScreenBrowsingMode = false;
1292 // Initialize AdView for the free flavor.
1293 adView = findViewById(R.id.adview);
1295 // Initialize the privacy settings variables.
1296 javaScriptEnabled = false;
1297 firstPartyCookiesEnabled = false;
1298 thirdPartyCookiesEnabled = false;
1299 domStorageEnabled = false;
1300 saveFormDataEnabled = false;
1303 // Initialize `webViewTitle`.
1304 webViewTitle = getString(R.string.no_title);
1306 // Initialize `favoriteIconBitmap`. `ContextCompat` must be used until API >= 21.
1307 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1308 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1309 assert favoriteIconBitmapDrawable != null;
1310 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1312 // If the favorite icon is null, load the default.
1313 if (favoriteIconBitmap == null) {
1314 favoriteIconBitmap = favoriteIconDefaultBitmap;
1317 // Apply the app settings from the shared preferences.
1320 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1321 if (!waitingForOrbot) {
1322 loadUrl(formattedUrlString);
1327 protected void onNewIntent(Intent intent) {
1328 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1331 if (intent.getData() != null) {
1332 // Get the intent data and convert it to a string.
1333 final Uri intentUriData = intent.getData();
1334 formattedUrlString = intentUriData.toString();
1337 // Close the navigation drawer if it is open.
1338 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1339 drawerLayout.closeDrawer(GravityCompat.START);
1342 // Load the website.
1343 loadUrl(formattedUrlString);
1345 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1346 mainWebView.requestFocus();
1350 public void onRestart() {
1351 // Run the default commands.
1354 // Apply the app settings, which may have been changed in `SettingsActivity`.
1357 // Apply the domain settings if returning from the Domains Activity.
1358 if (reapplyDomainSettingsOnRestart) {
1359 // Reset `reapplyDomainSettingsOnRestart`.
1360 reapplyDomainSettingsOnRestart = false;
1362 // Reapply the domain settings.
1363 applyDomainSettings(formattedUrlString);
1366 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1367 updatePrivacyIcons(true);
1369 // Set the display webpage images mode.
1370 setDisplayWebpageImages();
1372 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1373 if (reloadOnRestart) {
1374 // Reload `mainWebView`.
1375 mainWebView.reload();
1377 // Reset `reloadOnRestartBoolean`.
1378 reloadOnRestart = false;
1381 // Load the URL on restart to apply changes to night mode.
1382 if (loadUrlOnRestart) {
1383 // Load the current `formattedUrlString`.
1384 loadUrl(formattedUrlString);
1386 // Reset `loadUrlOnRestart.
1387 loadUrlOnRestart = false;
1391 if (restartFromBookmarksActivity) {
1392 // Close the bookmarks drawer.
1393 drawerLayout.closeDrawer(GravityCompat.END);
1395 // Reload the bookmarks drawer.
1396 loadBookmarksFolder();
1398 // Reset `restartFromBookmarksActivity`.
1399 restartFromBookmarksActivity = false;
1403 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1405 public void onResume() {
1406 // Run the default commands.
1409 // Resume JavaScript (if enabled).
1410 mainWebView.resumeTimers();
1412 // Resume `mainWebView`.
1413 mainWebView.onResume();
1415 // Resume the adView for the free flavor.
1416 if (BuildConfig.FLAVOR.contentEquals("free")) {
1417 BannerAd.resumeAd(adView);
1422 public void onPause() {
1423 // Pause `mainWebView`.
1424 mainWebView.onPause();
1426 // Stop all JavaScript.
1427 mainWebView.pauseTimers();
1429 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1430 if (BuildConfig.FLAVOR.contentEquals("free")) {
1431 BannerAd.pauseAd(adView);
1438 public boolean onCreateOptionsMenu(Menu menu) {
1439 // Inflate the menu; this adds items to the action bar if it is present.
1440 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1442 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1445 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1446 updatePrivacyIcons(false);
1448 // Get handles for the menu items.
1449 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1450 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1451 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1452 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1454 // Only display third-party cookies if SDK >= 21
1455 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1457 // Get the shared preference values. `this` references the current context.
1458 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1460 // Set the status of the additional app bar icons. The default is `false`.
1461 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1462 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1463 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1464 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1465 } else { //Do not display the additional icons.
1466 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1467 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1468 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1475 public boolean onPrepareOptionsMenu(Menu menu) {
1476 // Get handles for the menu items.
1477 MenuItem addOrEditDomain = menu.findItem(R.id.add_or_edit_domain);
1478 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1479 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1480 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1481 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1482 MenuItem clearDataMenuItem = menu.findItem(R.id.clear_data);
1483 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1484 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1485 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1486 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1487 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1488 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1490 // Set the text for the domain menu item.
1491 if (domainSettingsApplied) {
1492 addOrEditDomain.setTitle(R.string.edit_domain_settings);
1494 addOrEditDomain.setTitle(R.string.add_domain_settings);
1497 // Set the status of the menu item checkboxes.
1498 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1499 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1500 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1501 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1502 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1504 // Enable third-party cookies if first-party cookies are enabled.
1505 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1507 // Enable `DOM Storage` if JavaScript is enabled.
1508 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1510 // Enable `Clear Cookies` if there are any.
1511 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1513 // Get a count of the number of files in the `Local Storage` directory.
1514 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1515 int localStorageDirectoryNumberOfFiles = 0;
1516 if (localStorageDirectory.exists()) {
1517 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1520 // Get a count of the number of files in the `IndexedDB` directory.
1521 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1522 int indexedDBDirectoryNumberOfFiles = 0;
1523 if (indexedDBDirectory.exists()) {
1524 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1527 // Enable `Clear DOM Storage` if there is any.
1528 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1530 // Enable `Clear Form Data` is there is any.
1531 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1532 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1534 // Enable `Clear Data` if any of the submenu items are enabled.
1535 clearDataMenuItem.setEnabled(clearCookiesMenuItem.isEnabled() || clearDOMStorageMenuItem.isEnabled() || clearFormDataMenuItem.isEnabled());
1537 // Initialize font size variables.
1538 int fontSize = mainWebView.getSettings().getTextZoom();
1539 String fontSizeTitle;
1540 MenuItem selectedFontSizeMenuItem;
1542 // Prepare the font size title and current size menu item.
1545 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1546 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1550 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1551 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1555 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1556 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1560 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1561 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1565 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1566 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1570 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1571 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1575 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1576 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1580 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1581 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1585 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1586 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1590 // Set the font size title and select the current size menu item.
1591 fontSizeMenuItem.setTitle(fontSizeTitle);
1592 selectedFontSizeMenuItem.setChecked(true);
1594 // Only show `Refresh` if `swipeToRefresh` is disabled.
1595 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1597 // Run all the other default commands.
1598 super.onPrepareOptionsMenu(menu);
1600 // Display the menu.
1605 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1606 @SuppressLint("SetJavaScriptEnabled")
1607 // removeAllCookies is deprecated, but it is required for API < 21.
1608 @SuppressWarnings("deprecation")
1609 public boolean onOptionsItemSelected(MenuItem menuItem) {
1610 // Get the selected menu item ID.
1611 int menuItemId = menuItem.getItemId();
1613 // Set the commands that relate to the menu entries.
1614 switch (menuItemId) {
1615 case R.id.add_or_edit_domain:
1616 if (domainSettingsApplied) { // Edit the current domain settings.
1617 // Reapply the domain settings on returning to `MainWebViewActivity`.
1618 reapplyDomainSettingsOnRestart = true;
1619 currentDomainName = "";
1621 // Create an intent to launch the domains activity.
1622 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1624 // Put extra information instructing the domains activity to directly load the current domain.
1625 domainsIntent.putExtra("LoadDomain", domainSettingsDatabaseId);
1628 startActivity(domainsIntent);
1629 } else { // Add a new domain.
1630 // Show the add domain `AlertDialog`.
1631 AppCompatDialogFragment addDomainDialog = new AddDomainDialog();
1632 addDomainDialog.show(getSupportFragmentManager(), getResources().getString(R.string.add_domain));
1636 case R.id.toggle_javascript:
1637 // Switch the status of javaScriptEnabled.
1638 javaScriptEnabled = !javaScriptEnabled;
1640 // Apply the new JavaScript status.
1641 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1643 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1644 updatePrivacyIcons(true);
1646 // Display a `Snackbar`.
1647 if (javaScriptEnabled) { // JavaScrip is enabled.
1648 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1649 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1650 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1651 } else { // Privacy mode.
1652 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1655 // Reload the WebView.
1656 mainWebView.reload();
1659 case R.id.toggle_first_party_cookies:
1660 // Switch the status of firstPartyCookiesEnabled.
1661 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1663 // Update the menu checkbox.
1664 menuItem.setChecked(firstPartyCookiesEnabled);
1666 // Apply the new cookie status.
1667 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1669 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1670 updatePrivacyIcons(true);
1672 // Display a `Snackbar`.
1673 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1674 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1675 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1676 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1677 } else { // Privacy mode.
1678 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1681 // Reload the WebView.
1682 mainWebView.reload();
1685 case R.id.toggle_third_party_cookies:
1686 if (Build.VERSION.SDK_INT >= 21) {
1687 // Switch the status of thirdPartyCookiesEnabled.
1688 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1690 // Update the menu checkbox.
1691 menuItem.setChecked(thirdPartyCookiesEnabled);
1693 // Apply the new cookie status.
1694 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1696 // Display a `Snackbar`.
1697 if (thirdPartyCookiesEnabled) {
1698 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1700 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1703 // Reload the WebView.
1704 mainWebView.reload();
1705 } // Else do nothing because SDK < 21.
1708 case R.id.toggle_dom_storage:
1709 // Switch the status of domStorageEnabled.
1710 domStorageEnabled = !domStorageEnabled;
1712 // Update the menu checkbox.
1713 menuItem.setChecked(domStorageEnabled);
1715 // Apply the new DOM Storage status.
1716 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1718 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1719 updatePrivacyIcons(true);
1721 // Display a `Snackbar`.
1722 if (domStorageEnabled) {
1723 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1725 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1728 // Reload the WebView.
1729 mainWebView.reload();
1732 case R.id.toggle_save_form_data:
1733 // Switch the status of saveFormDataEnabled.
1734 saveFormDataEnabled = !saveFormDataEnabled;
1736 // Update the menu checkbox.
1737 menuItem.setChecked(saveFormDataEnabled);
1739 // Apply the new form data status.
1740 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1742 // Display a `Snackbar`.
1743 if (saveFormDataEnabled) {
1744 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1746 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1749 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1750 updatePrivacyIcons(true);
1752 // Reload the WebView.
1753 mainWebView.reload();
1756 case R.id.clear_cookies:
1757 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1758 .setAction(R.string.undo, v -> {
1759 // Do nothing because everything will be handled by `onDismissed()` below.
1761 .addCallback(new Snackbar.Callback() {
1763 public void onDismissed(Snackbar snackbar, int event) {
1765 // The user pushed the `Undo` button.
1766 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1770 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1772 // `cookieManager.removeAllCookie()` varies by SDK.
1773 if (Build.VERSION.SDK_INT < 21) {
1774 cookieManager.removeAllCookie();
1776 // `null` indicates no callback.
1777 cookieManager.removeAllCookies(null);
1785 case R.id.clear_dom_storage:
1786 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1787 .setAction(R.string.undo, v -> {
1788 // Do nothing because everything will be handled by `onDismissed()` below.
1790 .addCallback(new Snackbar.Callback() {
1792 public void onDismissed(Snackbar snackbar, int event) {
1794 // The user pushed the `Undo` button.
1795 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1799 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1801 // Delete the DOM Storage.
1802 WebStorage webStorage = WebStorage.getInstance();
1803 webStorage.deleteAllData();
1805 // Manually delete the DOM storage files and directories.
1807 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
1808 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1810 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
1811 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1812 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1813 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1814 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1815 } catch (IOException e) {
1816 // Do nothing if an error is thrown.
1824 case R.id.clear_form_data:
1825 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1826 .setAction(R.string.undo, v -> {
1827 // Do nothing because everything will be handled by `onDismissed()` below.
1829 .addCallback(new Snackbar.Callback() {
1831 public void onDismissed(Snackbar snackbar, int event) {
1833 // The user pushed the `Undo` button.
1834 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1838 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1840 // Delete the form data.
1841 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1842 mainWebViewDatabase.clearFormData();
1849 case R.id.font_size_twenty_five_percent:
1850 mainWebView.getSettings().setTextZoom(25);
1853 case R.id.font_size_fifty_percent:
1854 mainWebView.getSettings().setTextZoom(50);
1857 case R.id.font_size_seventy_five_percent:
1858 mainWebView.getSettings().setTextZoom(75);
1861 case R.id.font_size_one_hundred_percent:
1862 mainWebView.getSettings().setTextZoom(100);
1865 case R.id.font_size_one_hundred_twenty_five_percent:
1866 mainWebView.getSettings().setTextZoom(125);
1869 case R.id.font_size_one_hundred_fifty_percent:
1870 mainWebView.getSettings().setTextZoom(150);
1873 case R.id.font_size_one_hundred_seventy_five_percent:
1874 mainWebView.getSettings().setTextZoom(175);
1877 case R.id.font_size_two_hundred_percent:
1878 mainWebView.getSettings().setTextZoom(200);
1881 case R.id.display_images:
1882 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1883 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1884 mainWebView.reload();
1885 } else { // Images are not currently loaded automatically.
1886 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1889 // Set `onTheFlyDisplayImagesSet`.
1890 onTheFlyDisplayImagesSet = true;
1894 // Setup the share string.
1895 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1897 // Create the share intent.
1898 Intent shareIntent = new Intent();
1899 shareIntent.setAction(Intent.ACTION_SEND);
1900 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1901 shareIntent.setType("text/plain");
1904 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1907 case R.id.find_on_page:
1908 // Hide the URL app bar.
1909 supportAppBar.setVisibility(View.GONE);
1911 // Show the Find on Page `RelativeLayout`.
1912 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1914 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1915 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1916 findOnPageEditText.postDelayed(() -> {
1917 // Set the focus on `findOnPageEditText`.
1918 findOnPageEditText.requestFocus();
1920 // Display the keyboard. `0` sets no input flags.
1921 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1926 // Get a `PrintManager` instance.
1927 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1929 // Convert `mainWebView` to `printDocumentAdapter`.
1930 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1932 // Remove the lint error below that `printManager` might be `null`.
1933 assert printManager != null;
1935 // Print the document. The print attributes are `null`.
1936 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1939 case R.id.view_source:
1940 // Launch the Vew Source activity.
1941 Intent viewSourceIntent = new Intent(this, ViewSourceActivity.class);
1942 startActivity(viewSourceIntent);
1945 case R.id.add_to_homescreen:
1946 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1947 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1948 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1950 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1954 mainWebView.reload();
1958 // Don't consume the event.
1959 return super.onOptionsItemSelected(menuItem);
1963 // removeAllCookies is deprecated, but it is required for API < 21.
1964 @SuppressWarnings("deprecation")
1966 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1967 int menuItemId = menuItem.getItemId();
1969 switch (menuItemId) {
1975 if (mainWebView.canGoBack()) {
1976 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1977 navigatingHistory = true;
1979 // Load the previous website in the history.
1980 mainWebView.goBack();
1985 if (mainWebView.canGoForward()) {
1986 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1987 navigatingHistory = true;
1989 // Load the next website in the history.
1990 mainWebView.goForward();
1995 // Get the `WebBackForwardList`.
1996 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1998 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1999 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
2000 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
2003 case R.id.downloads:
2004 // Launch the system Download Manager.
2005 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
2007 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
2008 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2010 startActivity(downloadManagerIntent);
2014 // Reapply the domain settings on returning to `MainWebViewActivity`.
2015 reapplyDomainSettingsOnRestart = true;
2016 currentDomainName = "";
2018 // Launch `DomainsActivity`.
2019 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2020 startActivity(domainsIntent);
2024 // Reapply the domain settings on returning to `MainWebViewActivity`.
2025 reapplyDomainSettingsOnRestart = true;
2026 currentDomainName = "";
2028 // Launch `SettingsActivity`.
2029 Intent settingsIntent = new Intent(this, SettingsActivity.class);
2030 startActivity(settingsIntent);
2034 // Launch `GuideActivity`.
2035 Intent guideIntent = new Intent(this, GuideActivity.class);
2036 startActivity(guideIntent);
2040 // Launch `AboutActivity`.
2041 Intent aboutIntent = new Intent(this, AboutActivity.class);
2042 startActivity(aboutIntent);
2045 case R.id.clearAndExit:
2046 // Get a handle for `sharedPreferences`. `this` references the current context.
2047 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2049 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
2052 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
2053 // The command to remove cookies changed slightly in API 21.
2054 if (Build.VERSION.SDK_INT >= 21) {
2055 cookieManager.removeAllCookies(null);
2057 cookieManager.removeAllCookie();
2060 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2062 // We have to use two commands because `Runtime.exec()` does not like `*`.
2063 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2064 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2065 } catch (IOException e) {
2066 // Do nothing if an error is thrown.
2070 // Clear DOM storage.
2071 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2072 // Ask `WebStorage` to clear the DOM storage.
2073 WebStorage webStorage = WebStorage.getInstance();
2074 webStorage.deleteAllData();
2076 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2078 // A `String[]` must be used because the directory contains a space and `Runtime.exec` will otherwise not escape the string correctly.
2079 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2081 // Multiple commands must be used because `Runtime.exec()` does not like `*`.
2082 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2083 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2084 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2085 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2086 } catch (IOException e) {
2087 // Do nothing if an error is thrown.
2092 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2093 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2094 webViewDatabase.clearFormData();
2096 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2098 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2099 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2100 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2101 } catch (IOException e) {
2102 // Do nothing if an error is thrown.
2107 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2108 // `true` includes disk files.
2109 mainWebView.clearCache(true);
2111 // Manually delete the cache directories.
2113 // Delete the main cache directory.
2114 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2115 // Delete the secondary `Service Worker` cache directory.
2116 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2117 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2118 } catch (IOException e) {
2119 // Do nothing if an error is thrown.
2123 // Clear SSL certificate preferences.
2124 mainWebView.clearSslPreferences();
2126 // Clear the back/forward history.
2127 mainWebView.clearHistory();
2129 // Clear `formattedUrlString`.
2130 formattedUrlString = null;
2132 // Clear `customHeaders`.
2133 customHeaders.clear();
2135 // Detach all views from `mainWebViewRelativeLayout`.
2136 mainWebViewRelativeLayout.removeAllViews();
2138 // Destroy the internal state of `mainWebView`.
2139 mainWebView.destroy();
2141 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2142 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2143 if (clearEverything) {
2145 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2146 } catch (IOException e) {
2147 // Do nothing if an error is thrown.
2151 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2152 if (Build.VERSION.SDK_INT >= 21) {
2153 finishAndRemoveTask();
2158 // Remove the terminated program from RAM. The status code is `0`.
2163 // Close the navigation drawer.
2164 drawerLayout.closeDrawer(GravityCompat.START);
2169 public void onPostCreate(Bundle savedInstanceState) {
2170 super.onPostCreate(savedInstanceState);
2172 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2173 drawerToggle.syncState();
2177 public void onConfigurationChanged(Configuration newConfig) {
2178 super.onConfigurationChanged(newConfig);
2180 // Reload the ad for the free flavor if we are not in full screen mode.
2181 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2183 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2185 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2186 adView = findViewById(R.id.adview);
2189 // `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:
2190 // https://code.google.com/p/android/issues/detail?id=20493#c8
2191 // ActivityCompat.invalidateOptionsMenu(this);
2195 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2196 // Store the `HitTestResult`.
2197 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2200 final String imageUrl;
2201 final String linkUrl;
2203 // Get a handle for the `ClipboardManager`.
2204 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2206 // Remove the lint errors below that `clipboardManager` might be `null`.
2207 assert clipboardManager != null;
2209 switch (hitTestResult.getType()) {
2210 // `SRC_ANCHOR_TYPE` is a link.
2211 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2212 // Get the target URL.
2213 linkUrl = hitTestResult.getExtra();
2215 // Set the target URL as the title of the `ContextMenu`.
2216 menu.setHeaderTitle(linkUrl);
2218 // Add a `Load URL` entry.
2219 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
2224 // Add a `Copy URL` entry.
2225 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2226 // Save the link URL in a `ClipData`.
2227 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2229 // Set the `ClipData` as the clipboard's primary clip.
2230 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2234 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2235 menu.add(R.string.cancel);
2238 case WebView.HitTestResult.EMAIL_TYPE:
2239 // Get the target URL.
2240 linkUrl = hitTestResult.getExtra();
2242 // Set the target URL as the title of the `ContextMenu`.
2243 menu.setHeaderTitle(linkUrl);
2245 // Add a `Write Email` entry.
2246 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2247 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2248 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2250 // Parse the url and set it as the data for the `Intent`.
2251 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2253 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2254 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2257 startActivity(emailIntent);
2261 // Add a `Copy Email Address` entry.
2262 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2263 // Save the email address in a `ClipData`.
2264 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2266 // Set the `ClipData` as the clipboard's primary clip.
2267 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2271 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2272 menu.add(R.string.cancel);
2275 // `IMAGE_TYPE` is an image.
2276 case WebView.HitTestResult.IMAGE_TYPE:
2277 // Get the image URL.
2278 imageUrl = hitTestResult.getExtra();
2280 // Set the image URL as the title of the `ContextMenu`.
2281 menu.setHeaderTitle(imageUrl);
2283 // Add a `View Image` entry.
2284 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2289 // Add a `Download Image` entry.
2290 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2291 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2292 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2293 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2297 // Add a `Copy URL` entry.
2298 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2299 // Save the image URL in a `ClipData`.
2300 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2302 // Set the `ClipData` as the clipboard's primary clip.
2303 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2307 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2308 menu.add(R.string.cancel);
2312 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2313 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2314 // Get the image URL.
2315 imageUrl = hitTestResult.getExtra();
2317 // Set the image URL as the title of the `ContextMenu`.
2318 menu.setHeaderTitle(imageUrl);
2320 // Add a `View Image` entry.
2321 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2326 // Add a `Download Image` entry.
2327 menu.add(R.string.download_image).setOnMenuItemClickListener((MenuItem item) -> {
2328 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2329 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2330 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2334 // Add a `Copy URL` entry.
2335 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2336 // Save the image URL in a `ClipData`.
2337 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2339 // Set the `ClipData` as the clipboard's primary clip.
2340 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2344 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2345 menu.add(R.string.cancel);
2351 public void onAddDomain(AppCompatDialogFragment dialogFragment) {
2352 // Reapply the domain settings on returning to `MainWebViewActivity`.
2353 reapplyDomainSettingsOnRestart = true;
2354 currentDomainName = "";
2356 // Get the new domain name `String` from `dialogFragment`.
2357 EditText domainNameEditText = dialogFragment.getDialog().findViewById(R.id.domain_name_edittext);
2358 String domainNameString = domainNameEditText.getText().toString();
2360 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2361 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2362 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2364 // Create the domain and store the database ID in `currentDomainDatabaseId`.
2365 int newDomainDatabaseId = domainsDatabaseHelper.addDomain(domainNameString);
2367 // Create an intent to launch the domains activity.
2368 Intent domainsIntent = new Intent(this, DomainsActivity.class);
2370 // Put extra information instructing the domains activity to directly load the current domain.
2371 domainsIntent.putExtra("LoadDomain", newDomainDatabaseId);
2374 startActivity(domainsIntent);
2378 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2379 // Get the `EditTexts` from the `dialogFragment`.
2380 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2381 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2383 // Extract the strings from the `EditTexts`.
2384 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2385 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2387 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2388 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2389 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2390 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2392 // Display the new bookmark below the current items in the (0 indexed) list.
2393 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2395 // Create the bookmark.
2396 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2398 // Update `bookmarksCursor` with the current contents of this folder.
2399 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2401 // Update the `ListView`.
2402 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2404 // Scroll to the new bookmark.
2405 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2409 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2410 // Get handles for the views in `dialogFragment`.
2411 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2412 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2413 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2415 // Get new folder name string.
2416 String folderNameString = createFolderNameEditText.getText().toString();
2418 // Get the new folder icon `Bitmap`.
2419 Bitmap folderIconBitmap;
2420 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2421 // Get the default folder icon and convert it to a `Bitmap`.
2422 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2423 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2424 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2425 } else { // Use the `WebView` favorite icon.
2426 folderIconBitmap = favoriteIconBitmap;
2429 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2430 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2431 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2432 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2434 // Move all the bookmarks down one in the display order.
2435 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2436 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2437 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2440 // Create the folder, which will be placed at the top of the `ListView`.
2441 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2443 // Update `bookmarksCursor` with the current contents of this folder.
2444 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2446 // Update the `ListView`.
2447 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2449 // Scroll to the new folder.
2450 bookmarksListView.setSelection(0);
2454 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2455 // Get the shortcut name.
2456 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2457 String shortcutNameString = shortcutNameEditText.getText().toString();
2459 // Convert the favorite icon bitmap to an `Icon`. `IconCompat` is required until API >= 26.
2460 IconCompat favoriteIcon = IconCompat.createWithBitmap(favoriteIconBitmap);
2462 // Setup the shortcut intent.
2463 Intent shortcutIntent = new Intent();
2464 shortcutIntent.setAction(Intent.ACTION_VIEW);
2465 shortcutIntent.setData(Uri.parse(formattedUrlString));
2467 // Create a shortcut info builder. The shortcut name becomes the shortcut ID.
2468 ShortcutInfoCompat.Builder shortcutInfoBuilder = new ShortcutInfoCompat.Builder(this, shortcutNameString);
2470 // Add the required fields to the shortcut info builder.
2471 shortcutInfoBuilder.setIcon(favoriteIcon);
2472 shortcutInfoBuilder.setIntent(shortcutIntent);
2473 shortcutInfoBuilder.setShortLabel(shortcutNameString);
2475 // Request the pin. `ShortcutManagerCompat` can be switched to `ShortcutManager` once API >= 26.
2476 ShortcutManagerCompat.requestPinShortcut(this, shortcutInfoBuilder.build(), null);
2480 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2481 // Download the image if it has an HTTP or HTTPS URI.
2482 if (imageUrl.startsWith("http")) {
2483 // Get a handle for the system `DOWNLOAD_SERVICE`.
2484 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2486 // Parse `imageUrl`.
2487 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2489 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2490 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2491 if (firstPartyCookiesEnabled) {
2492 // Get the cookies for `imageUrl`.
2493 String cookies = cookieManager.getCookie(imageUrl);
2495 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2496 downloadRequest.addRequestHeader("Cookie", cookies);
2499 // Get the file name from `dialogFragment`.
2500 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2501 String imageName = downloadImageNameEditText.getText().toString();
2503 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2504 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2505 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2506 } else { // Only set the title using `imageName`.
2507 downloadRequest.setTitle(imageName);
2510 // Allow `MediaScanner` to index the download if it is a media file.
2511 downloadRequest.allowScanningByMediaScanner();
2513 // Add the URL as the description for the download.
2514 downloadRequest.setDescription(imageUrl);
2516 // Show the download notification after the download is completed.
2517 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2519 // Remove the lint warning below that `downloadManager` might be `null`.
2520 assert downloadManager != null;
2522 // Initiate the download.
2523 downloadManager.enqueue(downloadRequest);
2524 } else { // The image is not an HTTP or HTTPS URI.
2525 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2530 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2531 // Download the file if it has an HTTP or HTTPS URI.
2532 if (downloadUrl.startsWith("http")) {
2534 // Get a handle for the system `DOWNLOAD_SERVICE`.
2535 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2537 // Parse `downloadUrl`.
2538 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2540 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2541 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2542 if (firstPartyCookiesEnabled) {
2543 // Get the cookies for `downloadUrl`.
2544 String cookies = cookieManager.getCookie(downloadUrl);
2546 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2547 downloadRequest.addRequestHeader("Cookie", cookies);
2550 // Get the file name from `dialogFragment`.
2551 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2552 String fileName = downloadFileNameEditText.getText().toString();
2554 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2555 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2556 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2557 } else { // Only set the title using `fileName`.
2558 downloadRequest.setTitle(fileName);
2561 // Allow `MediaScanner` to index the download if it is a media file.
2562 downloadRequest.allowScanningByMediaScanner();
2564 // Add the URL as the description for the download.
2565 downloadRequest.setDescription(downloadUrl);
2567 // Show the download notification after the download is completed.
2568 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2570 // Remove the lint warning below that `downloadManager` might be `null`.
2571 assert downloadManager != null;
2573 // Initiate the download.
2574 downloadManager.enqueue(downloadRequest);
2575 } else { // The download is not an HTTP or HTTPS URI.
2576 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2581 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2582 // Get handles for the views from `dialogFragment`.
2583 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2584 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2585 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2587 // Store the bookmark strings.
2588 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2589 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2591 // Update the bookmark.
2592 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2593 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2594 } else { // Update the bookmark using the `WebView` favorite icon.
2595 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2596 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2597 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2598 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2600 // Update the bookmark and the favorite icon.
2601 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2604 // Update `bookmarksCursor` with the current contents of this folder.
2605 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2607 // Update the `ListView`.
2608 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2612 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2613 // Get handles for the views from `dialogFragment`.
2614 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2615 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2616 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2617 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2619 // Get the new folder name.
2620 String newFolderNameString = editFolderNameEditText.getText().toString();
2622 // Check if the favorite icon has changed.
2623 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2624 // Update the name in the database.
2625 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2626 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2627 // Get the new folder icon `Bitmap`.
2628 Bitmap folderIconBitmap;
2629 if (defaultFolderIconRadioButton.isChecked()) {
2630 // Get the default folder icon and convert it to a `Bitmap`.
2631 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2632 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2633 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2634 } else { // Use the `WebView` favorite icon.
2635 folderIconBitmap = favoriteIconBitmap;
2638 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2639 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2640 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2641 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2643 // Update the folder icon in the database.
2644 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2645 } else { // The folder icon and the name have changed.
2646 // Get the new folder icon `Bitmap`.
2647 Bitmap folderIconBitmap;
2648 if (defaultFolderIconRadioButton.isChecked()) {
2649 // Get the default folder icon and convert it to a `Bitmap`.
2650 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2651 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2652 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2653 } else { // Use the `WebView` favorite icon.
2654 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2657 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2658 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2659 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2660 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2662 // Update the folder name and icon in the database.
2663 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2666 // Update `bookmarksCursor` with the current contents of this folder.
2667 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2669 // Update the `ListView`.
2670 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2674 public void onHttpAuthenticationCancel() {
2675 // Cancel the `HttpAuthHandler`.
2676 httpAuthHandler.cancel();
2680 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2681 // Get handles for the `EditTexts`.
2682 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2683 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2685 // Proceed with the HTTP authentication.
2686 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2689 public void viewSslCertificate(View view) {
2690 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2691 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2692 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2696 public void onSslErrorCancel() {
2697 sslErrorHandler.cancel();
2701 public void onSslErrorProceed() {
2702 sslErrorHandler.proceed();
2706 public void onSslMismatchBack() {
2707 if (mainWebView.canGoBack()) { // There is a back page in the history.
2708 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2709 navigatingHistory = true;
2712 mainWebView.goBack();
2713 } else { // There are no pages to go back to.
2714 // Load a blank page
2720 public void onSslMismatchProceed() {
2721 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2722 ignorePinnedSslCertificate = true;
2726 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2727 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2728 navigatingHistory = true;
2730 // Load the history entry.
2731 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2735 public void onClearHistory() {
2736 // Clear the history.
2737 mainWebView.clearHistory();
2740 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2742 public void onBackPressed() {
2743 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2744 // Close the navigation drawer.
2745 drawerLayout.closeDrawer(GravityCompat.START);
2746 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2747 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2748 // close the bookmarks drawer.
2749 drawerLayout.closeDrawer(GravityCompat.END);
2750 } else { // A subfolder is displayed.
2751 // Place the former parent folder in `currentFolder`.
2752 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2754 // Load the new folder.
2755 loadBookmarksFolder();
2758 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2759 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2760 navigatingHistory = true;
2763 mainWebView.goBack();
2764 } else { // There isn't anything to do in Privacy Browser.
2765 // Pass `onBackPressed()` to the system.
2766 super.onBackPressed();
2770 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2771 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2772 String unformattedUrlString = urlTextBox.getText().toString().trim();
2774 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2775 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2776 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2777 if (!unformattedUrlString.startsWith("http")) {
2778 unformattedUrlString = "http://" + unformattedUrlString;
2781 // Initialize `unformattedUrl`.
2782 URL unformattedUrl = null;
2784 // 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.
2786 unformattedUrl = new URL(unformattedUrlString);
2787 } catch (MalformedURLException e) {
2788 e.printStackTrace();
2791 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2792 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2793 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2794 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2795 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2796 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2799 Uri.Builder formattedUri = new Uri.Builder();
2800 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2802 // Decode `formattedUri` as a `String` in `UTF-8`.
2803 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2805 // Sanitize the search input and convert it to a search.
2806 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2808 // Add the base search URL.
2809 formattedUrlString = searchURL + encodedUrlString;
2812 // 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.
2813 urlTextBox.clearFocus();
2815 loadUrl(formattedUrlString);
2819 private void loadUrl(String url) {
2820 // Apply any custom domain settings.
2821 applyDomainSettings(url);
2824 mainWebView.loadUrl(url, customHeaders);
2826 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2827 urlIsLoading = true;
2830 public void findPreviousOnPage(View view) {
2831 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2832 mainWebView.findNext(false);
2835 public void findNextOnPage(View view) {
2836 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2837 mainWebView.findNext(true);
2840 public void closeFindOnPage(View view) {
2841 // Delete the contents of `find_on_page_edittext`.
2842 findOnPageEditText.setText(null);
2844 // Clear the highlighted phrases.
2845 mainWebView.clearMatches();
2847 // Hide the Find on Page `RelativeLayout`.
2848 findOnPageLinearLayout.setVisibility(View.GONE);
2850 // Show the URL app bar.
2851 supportAppBar.setVisibility(View.VISIBLE);
2853 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2854 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2857 private void applyAppSettings() {
2858 // Get a handle for the shared preferences.
2859 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2861 // Store the values from the shared preferences in variables.
2862 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2863 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2864 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2865 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2866 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2867 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2868 easyListEnabled = sharedPreferences.getBoolean("easylist", true);
2869 easyPrivacyEnabled = sharedPreferences.getBoolean("easyprivacy", true);
2870 fanboyAnnoyanceListEnabled = sharedPreferences.getBoolean("fanboy_annoyance_list", true);
2871 fanboySocialBlockingListEnabled = sharedPreferences.getBoolean("fanboy_social_blocking_list", true);
2872 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2873 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2874 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2875 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2876 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2877 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2878 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2879 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2881 // Set the homepage, search, and proxy options.
2882 if (proxyThroughOrbot) { // Set the Tor options.
2883 // Set `torHomepageString` as `homepage`.
2884 homepage = torHomepageString;
2886 // If formattedUrlString is null assign the homepage to it.
2887 if (formattedUrlString == null) {
2888 formattedUrlString = homepage;
2891 // Set the search URL.
2892 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2893 searchURL = torSearchCustomURLString;
2894 } else { // Use the string from the pre-built list.
2895 searchURL = torSearchString;
2898 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2899 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2901 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2903 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2905 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2908 // Display a message to the user if we are waiting on Orbot.
2909 if (!orbotStatus.equals("ON")) {
2910 // Set `waitingForOrbot`.
2911 waitingForOrbot = true;
2913 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2914 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2916 } else { // Set the non-Tor options.
2917 // Set `homepageString` as `homepage`.
2918 homepage = homepageString;
2920 // If formattedUrlString is null assign the homepage to it.
2921 if (formattedUrlString == null) {
2922 formattedUrlString = homepage;
2925 // Set the search URL.
2926 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2927 searchURL = searchCustomURLString;
2928 } else { // Use the string from the pre-built list.
2929 searchURL = searchString;
2932 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2933 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2935 // Set the default `appBar` background. `this` refers to the context.
2937 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2939 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2942 // Reset `waitingForOrbot.
2943 waitingForOrbot = false;
2946 // Set swipe to refresh.
2947 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2949 // Set Do Not Track status.
2950 if (doNotTrackEnabled) {
2951 customHeaders.put("DNT", "1");
2953 customHeaders.remove("DNT");
2956 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2957 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2958 if (hideSystemBarsOnFullscreen) { // Hide everything.
2959 // Remove the translucent navigation setting if it is currently flagged.
2960 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2962 // Remove the translucent status bar overlay.
2963 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2965 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2966 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2968 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2969 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2970 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically re-hides them after they are shown.
2972 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2973 } else { // Hide everything except the status and navigation bars.
2974 // Add the translucent status flag if it is unset.
2975 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2977 if (translucentNavigationBarOnFullscreen) {
2978 // Set the navigation bar to be translucent.
2979 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2981 // Set the navigation bar to be black.
2982 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2985 } else { // Switch to normal viewing mode.
2986 // Reset `inFullScreenBrowsingMode` to `false`.
2987 inFullScreenBrowsingMode = false;
2989 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2990 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2994 // Show the `BannerAd` in the free flavor.
2995 if (BuildConfig.FLAVOR.contentEquals("free")) {
2996 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2997 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2999 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
3000 adView = findViewById(R.id.adview);
3003 // Remove the translucent navigation bar flag if it is set.
3004 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
3006 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
3007 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
3009 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
3010 rootCoordinatorLayout.setSystemUiVisibility(0);
3012 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
3013 rootCoordinatorLayout.setFitsSystemWindows(true);
3017 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3018 @SuppressWarnings("deprecation")
3019 private void applyDomainSettings(String url) {
3020 // Reset `navigatingHistory`.
3021 navigatingHistory = false;
3023 // Parse the URL into a URI.
3024 Uri uri = Uri.parse(url);
3026 // Extract the domain from `uri`.
3027 String hostName = uri.getHost();
3029 // Initialize `loadingNewDomainName`.
3030 boolean loadingNewDomainName;
3032 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
3033 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
3034 //noinspection SimplifiableIfStatement
3035 if ((hostName == null) || (currentDomainName == null)) {
3036 loadingNewDomainName = true;
3037 } else { // Determine if `hostName` equals `currentDomainName`.
3038 loadingNewDomainName = !hostName.equals(currentDomainName);
3041 // 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.
3042 if (loadingNewDomainName) {
3043 // Set the new `hostname` as the `currentDomainName`.
3044 currentDomainName = hostName;
3046 // Reset `ignorePinnedSslCertificate`.
3047 ignorePinnedSslCertificate = false;
3049 // Reset `favoriteIconBitmap` and display it in the `appbar`.
3050 favoriteIconBitmap = favoriteIconDefaultBitmap;
3051 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
3053 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
3054 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
3055 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
3057 // Get a full cursor from `domainsDatabaseHelper`.
3058 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
3060 // Initialize `domainSettingsSet`.
3061 Set<String> domainSettingsSet = new HashSet<>();
3063 // Get the domain name column index.
3064 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
3066 // Populate `domainSettingsSet`.
3067 for (int i = 0; i < domainNameCursor.getCount(); i++) {
3068 // Move `domainsCursor` to the current row.
3069 domainNameCursor.moveToPosition(i);
3071 // Store the domain name in `domainSettingsSet`.
3072 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
3075 // Close `domainNameCursor.
3076 domainNameCursor.close();
3078 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3079 domainSettingsApplied = false;
3080 String domainNameInDatabase = null;
3082 // Check the hostname.
3083 if (domainSettingsSet.contains(hostName)) {
3084 domainSettingsApplied = true;
3085 domainNameInDatabase = hostName;
3088 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3089 if (hostName != null) {
3090 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3091 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3092 domainSettingsApplied = true;
3093 domainNameInDatabase = "*." + hostName;
3096 // Strip out the lowest subdomain of `host`.
3097 hostName = hostName.substring(hostName.indexOf(".") + 1);
3101 // Get a handle for the shared preference. `this` references the current context.
3102 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3104 // Store the general preference information.
3105 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3106 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3107 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3108 nightMode = sharedPreferences.getBoolean("night_mode", false);
3110 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3111 // Get a cursor for the current host and move it to the first position.
3112 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3113 currentHostDomainSettingsCursor.moveToFirst();
3115 // Get the settings from the cursor.
3116 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3117 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3118 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3119 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3120 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3121 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3122 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3123 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3124 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3125 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3126 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3127 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3128 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3129 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3130 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3131 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3132 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3134 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3135 switch (nightModeInt) {
3136 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3140 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3145 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3147 javaScriptEnabled = true;
3150 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3151 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3152 pinnedDomainSslStartDate = null;
3154 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3157 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3158 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3159 pinnedDomainSslEndDate = null;
3161 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3164 // Close `currentHostDomainSettingsCursor`.
3165 currentHostDomainSettingsCursor.close();
3167 // Apply the domain settings.
3168 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3169 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3170 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3171 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3173 // Apply the font size.
3174 if (fontSize == 0) { // Apply the default font size.
3175 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3176 } else { // Apply the specified font size.
3177 mainWebView.getSettings().setTextZoom(fontSize);
3180 // Set third-party cookies status if API >= 21.
3181 if (Build.VERSION.SDK_INT >= 21) {
3182 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3185 // 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.
3186 // <https://redmine.stoutner.com/issues/160>
3187 if (!urlIsLoading) {
3188 switch (userAgentString) {
3189 case "System default user agent":
3190 // Set the user agent according to the system default.
3191 switch (defaultUserAgentString) {
3192 case "WebView default user agent":
3193 // Set the user agent to `""`, which uses the default value.
3194 mainWebView.getSettings().setUserAgentString("");
3197 case "Custom user agent":
3198 // Set the custom user agent.
3199 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3203 // Use the selected user agent.
3204 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3208 case "WebView default user agent":
3209 // Set the user agent to `""`, which uses the default value.
3210 mainWebView.getSettings().setUserAgentString("");
3214 // Use the selected user agent.
3215 mainWebView.getSettings().setUserAgentString(userAgentString);
3218 // Store the applied user agent string.
3219 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3222 // 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.
3224 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3226 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3228 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3229 // Store the values from `sharedPreferences` in variables.
3230 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3231 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3232 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3233 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3234 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3236 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3238 javaScriptEnabled = true;
3241 // Apply the default settings.
3242 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3243 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3244 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3245 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3246 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3248 // Reset the pinned SSL certificate information.
3249 domainSettingsDatabaseId = -1;
3250 pinnedDomainSslCertificate = false;
3251 pinnedDomainSslIssuedToCNameString = "";
3252 pinnedDomainSslIssuedToONameString = "";
3253 pinnedDomainSslIssuedToUNameString = "";
3254 pinnedDomainSslIssuedByCNameString = "";
3255 pinnedDomainSslIssuedByONameString = "";
3256 pinnedDomainSslIssuedByUNameString = "";
3257 pinnedDomainSslStartDate = null;
3258 pinnedDomainSslEndDate = null;
3260 // Set third-party cookies status if API >= 21.
3261 if (Build.VERSION.SDK_INT >= 21) {
3262 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3265 // 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.
3266 // <https://redmine.stoutner.com/issues/160>
3267 if (!urlIsLoading) {
3268 switch (defaultUserAgentString) {
3269 case "WebView default user agent":
3270 // Set the user agent to `""`, which uses the default value.
3271 mainWebView.getSettings().setUserAgentString("");
3274 case "Custom user agent":
3275 // Set the custom user agent.
3276 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3280 // Use the selected user agent.
3281 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3284 // Store the applied user agent string.
3285 appliedUserAgentString = mainWebView.getSettings().getUserAgentString();
3288 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3289 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3292 // Close `domainsDatabaseHelper`.
3293 domainsDatabaseHelper.close();
3295 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3296 onTheFlyDisplayImagesSet = false;
3297 setDisplayWebpageImages();
3299 // Update the privacy icons, but only if `mainMenu` has already been populated.
3300 if (mainMenu != null) {
3301 updatePrivacyIcons(true);
3306 private void setDisplayWebpageImages() {
3307 if (!onTheFlyDisplayImagesSet) {
3308 if (domainSettingsApplied) { // Custom domain settings are applied.
3309 switch (displayWebpageImagesInt) {
3310 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3311 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3314 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3315 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3318 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3319 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3322 } else { // Default settings are applied.
3323 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3328 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3329 // Get handles for the icons.
3330 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3331 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3332 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3333 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3335 // Update `privacyIcon`.
3336 if (javaScriptEnabled) { // JavaScript is enabled.
3337 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3338 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3339 privacyIconMenuItem.setIcon(R.drawable.warning);
3340 } else { // All the dangerous features are disabled.
3341 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3344 // Update `firstPartyCookiesIcon`.
3345 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3346 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3347 } else { // First-party cookies are disabled.
3349 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3351 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3355 // Update `domStorageIcon`.
3356 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3357 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3358 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3360 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3362 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3364 } else { // JavaScript is disabled, so DOM storage is ghosted.
3366 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3368 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3372 // Update `formDataIcon`.
3373 if (saveFormDataEnabled) { // Form data is enabled.
3374 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3375 } else { // Form data is disabled.
3377 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3379 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3383 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
3384 if (runInvalidateOptionsMenu) {
3385 invalidateOptionsMenu();
3389 private void highlightUrlText() {
3390 String urlString = urlTextBox.getText().toString();
3392 if (urlString.startsWith("http://")) { // Highlight the protocol of connections that are not encrypted.
3393 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3394 } else if (urlString.startsWith("https://")) { // De-emphasize the protocol of connections that are encrypted.
3395 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3398 // Get the index of the `/` immediately after the domain name.
3399 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3401 // De-emphasize the text after the domain name.
3402 if (endOfDomainName > 0) {
3403 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3407 private void loadBookmarksFolder() {
3408 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3409 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3411 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3412 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3414 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3415 // Inflate the individual item layout. `false` does not attach it to the root.
3416 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3420 public void bindView(View view, Context context, Cursor cursor) {
3421 // Get handles for the views.
3422 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3423 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3425 // Get the favorite icon byte array from the `Cursor`.
3426 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3428 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3429 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3431 // Display the bitmap in `bookmarkFavoriteIcon`.
3432 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3434 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3435 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3436 bookmarkNameTextView.setText(bookmarkNameString);
3438 // Make the font bold for folders.
3439 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3440 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3441 } else { // Reset the font to default for normal bookmarks.
3442 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3447 // Populate the `ListView` with the adapter.
3448 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3450 // Set the bookmarks drawer title.
3451 if (currentBookmarksFolder.isEmpty()) {
3452 bookmarksTitleTextView.setText(R.string.bookmarks);
3454 bookmarksTitleTextView.setText(currentBookmarksFolder);