2 * Copyright © 2015-2017 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.annotation.SuppressLint;
25 import android.app.DialogFragment;
26 import android.app.DownloadManager;
27 import android.content.BroadcastReceiver;
28 import android.content.ClipData;
29 import android.content.ClipboardManager;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.SharedPreferences;
34 import android.content.res.Configuration;
35 import android.database.Cursor;
36 import android.graphics.Bitmap;
37 import android.graphics.BitmapFactory;
38 import android.graphics.Typeface;
39 import android.graphics.drawable.BitmapDrawable;
40 import android.graphics.drawable.Drawable;
41 import android.net.Uri;
42 import android.net.http.SslCertificate;
43 import android.net.http.SslError;
44 import android.os.Build;
45 import android.os.Bundle;
46 import android.os.Handler;
47 import android.preference.PreferenceManager;
48 import android.print.PrintDocumentAdapter;
49 import android.print.PrintManager;
50 import android.support.annotation.NonNull;
51 import android.support.design.widget.CoordinatorLayout;
52 import android.support.design.widget.FloatingActionButton;
53 import android.support.design.widget.NavigationView;
54 import android.support.design.widget.Snackbar;
55 import android.support.v4.app.ActivityCompat;
56 import android.support.v4.content.ContextCompat;
57 import android.support.v4.view.GravityCompat;
58 import android.support.v4.widget.DrawerLayout;
59 import android.support.v4.widget.SwipeRefreshLayout;
60 import android.support.v7.app.ActionBar;
61 import android.support.v7.app.ActionBarDrawerToggle;
62 import android.support.v7.app.AppCompatActivity;
63 import android.support.v7.app.AppCompatDialogFragment;
64 import android.support.v7.widget.Toolbar;
65 import android.text.Editable;
66 import android.text.Spanned;
67 import android.text.TextWatcher;
68 import android.text.style.ForegroundColorSpan;
69 import android.util.Patterns;
70 import android.view.ContextMenu;
71 import android.view.GestureDetector;
72 import android.view.KeyEvent;
73 import android.view.Menu;
74 import android.view.MenuItem;
75 import android.view.MotionEvent;
76 import android.view.View;
77 import android.view.ViewGroup;
78 import android.view.WindowManager;
79 import android.view.inputmethod.InputMethodManager;
80 import android.webkit.CookieManager;
81 import android.webkit.HttpAuthHandler;
82 import android.webkit.SslErrorHandler;
83 import android.webkit.WebBackForwardList;
84 import android.webkit.WebChromeClient;
85 import android.webkit.WebResourceResponse;
86 import android.webkit.WebStorage;
87 import android.webkit.WebView;
88 import android.webkit.WebViewClient;
89 import android.webkit.WebViewDatabase;
90 import android.widget.CursorAdapter;
91 import android.widget.EditText;
92 import android.widget.FrameLayout;
93 import android.widget.ImageView;
94 import android.widget.LinearLayout;
95 import android.widget.ListView;
96 import android.widget.ProgressBar;
97 import android.widget.RadioButton;
98 import android.widget.RelativeLayout;
99 import android.widget.TextView;
101 import com.stoutner.privacybrowser.BannerAd;
102 import com.stoutner.privacybrowser.BuildConfig;
103 import com.stoutner.privacybrowser.R;
104 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
105 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
106 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
107 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
108 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
109 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
110 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
111 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
112 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
113 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
114 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
115 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
116 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
117 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
118 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
120 import java.io.BufferedReader;
121 import java.io.ByteArrayInputStream;
122 import java.io.ByteArrayOutputStream;
124 import java.io.IOException;
125 import java.io.InputStreamReader;
126 import java.io.UnsupportedEncodingException;
127 import java.net.MalformedURLException;
129 import java.net.URLDecoder;
130 import java.net.URLEncoder;
131 import java.util.Date;
132 import java.util.HashMap;
133 import java.util.HashSet;
134 import java.util.Map;
135 import java.util.Set;
137 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
138 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
139 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener,
140 NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
142 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`,
143 // `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`,
144 // `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`, and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
145 public static boolean darkTheme;
147 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`,
148 // `EditBookmarkFolderDialog`, `EditBookmarkDatabaseViewDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`,
149 // `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
150 public static Bitmap favoriteIconBitmap;
152 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
153 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
154 public static String formattedUrlString;
156 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
157 public static SslCertificate sslCertificate;
159 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
160 public static String orbotStatus;
162 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
163 public static String webViewTitle;
165 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
166 public static boolean displayWebpageImagesBoolean;
168 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
169 public static boolean reloadOnRestart;
171 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
172 public static boolean loadUrlOnRestart;
174 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
175 public static boolean restartFromBookmarksActivity;
177 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and
178 // `loadBookmarksFolder()`.
179 public static String currentBookmarksFolder;
181 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
182 public static int domainSettingsDatabaseId;
183 public static String pinnedDomainSslIssuedToCNameString;
184 public static String pinnedDomainSslIssuedToONameString;
185 public static String pinnedDomainSslIssuedToUNameString;
186 public static String pinnedDomainSslIssuedByCNameString;
187 public static String pinnedDomainSslIssuedByONameString;
188 public static String pinnedDomainSslIssuedByUNameString;
189 public static Date pinnedDomainSslStartDate;
190 public static Date pinnedDomainSslEndDate;
193 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
194 private ActionBar appBar;
196 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
197 private boolean navigatingHistory;
199 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
200 private Bitmap favoriteIconDefaultBitmap;
202 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
203 private DrawerLayout drawerLayout;
205 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
206 private CoordinatorLayout rootCoordinatorLayout;
208 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
209 // `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
210 private WebView mainWebView;
212 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
213 private FrameLayout fullScreenVideoFrameLayout;
215 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
216 private SwipeRefreshLayout swipeRefreshLayout;
218 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
219 private RelativeLayout urlAppBarRelativeLayout;
221 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
222 private ImageView favoriteIconImageView;
224 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
225 private CookieManager cookieManager;
227 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
228 private final Map<String, String> customHeaders = new HashMap<>();
230 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
231 private boolean javaScriptEnabled;
233 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
234 private boolean firstPartyCookiesEnabled;
236 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
237 private boolean thirdPartyCookiesEnabled;
239 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
240 private boolean domStorageEnabled;
242 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
243 private boolean saveFormDataEnabled;
245 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
246 private boolean nightMode;
248 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
249 private boolean swipeToRefreshEnabled;
251 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
252 private String homepage;
254 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
255 private String searchURL;
257 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
258 private boolean adBlockerEnabled;
260 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
261 private Runtime privacyBrowserRuntime;
263 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
264 private boolean incognitoModeEnabled;
266 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
267 private boolean fullScreenBrowsingModeEnabled;
269 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
270 private boolean inFullScreenBrowsingMode;
272 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
273 private boolean hideSystemBarsOnFullscreen;
275 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
276 private boolean translucentNavigationBarOnFullscreen;
278 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
279 private String currentDomainName;
281 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
282 private boolean ignorePinnedSslCertificate;
284 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
285 private boolean waitingForOrbot;
287 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
288 private boolean domainSettingsApplied;
290 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
291 private int displayWebpageImagesInt;
293 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
294 private boolean onTheFlyDisplayImagesSet;
296 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
297 private String waitingForOrbotHTMLString;
299 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
300 private String privateDataDirectoryString;
302 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
303 private LinearLayout findOnPageLinearLayout;
305 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
306 private EditText findOnPageEditText;
308 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
309 private Menu mainMenu;
311 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
312 private ActionBarDrawerToggle drawerToggle;
314 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
315 private Toolbar supportAppBar;
317 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
318 private EditText urlTextBox;
320 // `redColorSpan` is used in `onCreate()` and `highlightUrlText()`.
321 private ForegroundColorSpan redColorSpan;
323 // `initialGrayColorSpan` is sued in `onCreate()` and `highlightUrlText()`.
324 private ForegroundColorSpan initialGrayColorSpan;
326 // `finalGrayColorSpam` is used in `onCreate()` and `highlightUrlText()`.
327 private ForegroundColorSpan finalGrayColorSpan;
329 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
332 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
333 private SslErrorHandler sslErrorHandler;
335 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
336 private static HttpAuthHandler httpAuthHandler;
338 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
339 private InputMethodManager inputMethodManager;
341 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
342 private RelativeLayout mainWebViewRelativeLayout;
344 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
345 private boolean urlIsLoading;
347 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
348 private boolean pinnedDomainSslCertificate;
350 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
351 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
353 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
354 private ListView bookmarksListView;
356 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
357 private TextView bookmarksTitleTextView;
359 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
360 private Cursor bookmarksCursor;
362 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
363 private CursorAdapter bookmarksCursorAdapter;
365 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
366 private String oldFolderNameString;
369 // 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.
370 @SuppressLint({"SetJavaScriptEnabled"})
371 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
372 @SuppressWarnings("deprecation")
373 protected void onCreate(Bundle savedInstanceState) {
374 // Get a handle for `sharedPreferences`. `this` references the current context.
375 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
377 // Get the theme preference.
378 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
380 // Set the activity theme.
382 setTheme(R.style.PrivacyBrowserDark);
384 setTheme(R.style.PrivacyBrowserLight);
387 // Run the default commands.
388 super.onCreate(savedInstanceState);
390 // Set the content view.
391 setContentView(R.layout.main_drawerlayout);
393 // Get a handle for `inputMethodManager`.
394 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
396 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
397 supportAppBar = findViewById(R.id.app_bar);
398 setSupportActionBar(supportAppBar);
399 appBar = getSupportActionBar();
401 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
402 assert appBar != null;
404 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
405 appBar.setCustomView(R.layout.url_app_bar);
406 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
408 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
409 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
410 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
411 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
413 // Get a handle for `urlTextBox`.
414 urlTextBox = appBar.getCustomView().findViewById(R.id.url_edittext);
416 // Remove the formatting from `urlTextBar` when the user is editing the text.
417 urlTextBox.setOnFocusChangeListener((v, hasFocus) -> {
418 if (hasFocus) { // The user is editing `urlTextBox`.
419 // Remove the highlighting.
420 urlTextBox.getText().removeSpan(redColorSpan);
421 urlTextBox.getText().removeSpan(initialGrayColorSpan);
422 urlTextBox.getText().removeSpan(finalGrayColorSpan);
423 } else { // The user has stopped editing `urlTextBox`.
424 // Reapply the highlighting.
429 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
430 urlTextBox.setOnKeyListener((v, keyCode, event) -> {
431 // If the event is a key-down event on the `enter` button, load the URL.
432 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
433 // Load the URL into the mainWebView and consume the event.
435 loadUrlFromTextBox();
436 } catch (UnsupportedEncodingException e) {
439 // If the enter key was pressed, consume the event.
442 // If any other key was pressed, do not consume the event.
447 // Set `waitingForOrbotHTMLString`.
448 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
450 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
451 currentDomainName = "";
452 orbotStatus = "unknown";
453 waitingForOrbot = false;
455 // Create an Orbot status `BroadcastReceiver`.
456 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
458 public void onReceive(Context context, Intent intent) {
459 // Store the content of the status message in `orbotStatus`.
460 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
462 // If we are waiting on Orbot, load the website now that Orbot is connected.
463 if (orbotStatus.equals("ON") && waitingForOrbot) {
464 // Reset `waitingForOrbot`.
465 waitingForOrbot = false;
467 // Load `formattedUrlString
468 loadUrl(formattedUrlString);
473 // Register `orbotStatusBroadcastReceiver` on `this` context.
474 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
476 // Get handles for views that need to be accessed.
477 drawerLayout = findViewById(R.id.drawerlayout);
478 rootCoordinatorLayout = findViewById(R.id.root_coordinatorlayout);
479 bookmarksListView = findViewById(R.id.bookmarks_drawer_listview);
480 bookmarksTitleTextView = findViewById(R.id.bookmarks_title_textview);
481 FloatingActionButton launchBookmarksActivityFab = findViewById(R.id.launch_bookmarks_activity_fab);
482 FloatingActionButton createBookmarkFolderFab = findViewById(R.id.create_bookmark_folder_fab);
483 FloatingActionButton createBookmarkFab = findViewById(R.id.create_bookmark_fab);
484 mainWebViewRelativeLayout = findViewById(R.id.main_webview_relativelayout);
485 mainWebView = findViewById(R.id.main_webview);
486 findOnPageLinearLayout = findViewById(R.id.find_on_page_linearlayout);
487 findOnPageEditText = findViewById(R.id.find_on_page_edittext);
488 fullScreenVideoFrameLayout = findViewById(R.id.full_screen_video_framelayout);
489 urlAppBarRelativeLayout = findViewById(R.id.url_app_bar_relativelayout);
490 favoriteIconImageView = findViewById(R.id.favorite_icon);
492 // 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.
494 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
495 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
496 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
497 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
499 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
500 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
501 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
502 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
505 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
506 launchBookmarksActivityFab.setOnClickListener(v -> {
507 // Create an intent to launch the bookmarks activity.
508 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
510 // Include the current folder with the `Intent`.
511 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
514 startActivity(bookmarksIntent);
517 // Set the create new bookmark folder FAB to display the `AlertDialog`.
518 createBookmarkFolderFab.setOnClickListener(v -> {
519 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
520 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
521 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
524 // Set the create new bookmark FAB to display the `AlertDialog`.
525 createBookmarkFab.setOnClickListener(view -> {
526 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
527 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
528 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
531 // Create a double-tap listener to toggle full-screen mode.
532 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
533 // Override `onDoubleTap()`. All other events are handled using the default settings.
535 public boolean onDoubleTap(MotionEvent event) {
536 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
537 // Toggle `inFullScreenBrowsingMode`.
538 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
540 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
541 // Hide the `appBar`.
544 // Hide the `BannerAd` in the free flavor.
545 if (BuildConfig.FLAVOR.contentEquals("free")) {
546 BannerAd.hideAd(adView);
549 // Modify the system bars.
550 if (hideSystemBarsOnFullscreen) { // Hide everything.
551 // Remove the translucent overlays.
552 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
554 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
555 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
557 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
558 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
559 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
561 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
563 // Set `rootCoordinatorLayout` to fill the whole screen.
564 rootCoordinatorLayout.setFitsSystemWindows(false);
565 } else { // Hide everything except the status and navigation bars.
566 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
567 rootCoordinatorLayout.setFitsSystemWindows(false);
569 if (translucentNavigationBarOnFullscreen) { // There is an Android Support Library bug that causes a scrim to print on the right side of the `Drawer Layout` when the navigation bar is displayed on the right of the screen.
570 // Set the navigation bar to be translucent.
571 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
574 } else { // Switch to normal viewing mode.
575 // Show the `appBar`.
578 // Show the `BannerAd` in the free flavor.
579 if (BuildConfig.FLAVOR.contentEquals("free")) {
580 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
581 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
583 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
584 adView = findViewById(R.id.adview);
587 // Remove the translucent navigation bar flag if it is set.
588 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
590 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
591 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
593 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
594 rootCoordinatorLayout.setSystemUiVisibility(0);
596 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
597 rootCoordinatorLayout.setFitsSystemWindows(true);
600 // Consume the double-tap.
602 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
608 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
609 mainWebView.setOnTouchListener((View v, MotionEvent event) -> {
610 // Call `performClick()` on the view, which is required for accessibility.
613 // Send the `event` to `gestureDetector`.
614 return gestureDetector.onTouchEvent(event);
617 // Update `findOnPageCountTextView`.
618 mainWebView.setFindListener(new WebView.FindListener() {
619 // Get a handle for `findOnPageCountTextView`.
620 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
623 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
624 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
625 // Set `findOnPageCountTextView` to `0/0`.
626 findOnPageCountTextView.setText(R.string.zero_of_zero);
627 } else if (isDoneCounting) { // There are matches.
628 // `activeMatchOrdinal` is zero-based.
629 int activeMatch = activeMatchOrdinal + 1;
631 // Build the match string.
632 String matchString = activeMatch + "/" + numberOfMatches;
634 // Set `findOnPageCountTextView`.
635 findOnPageCountTextView.setText(matchString);
640 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
641 findOnPageEditText.addTextChangedListener(new TextWatcher() {
643 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
648 public void onTextChanged(CharSequence s, int start, int before, int count) {
653 public void afterTextChanged(Editable s) {
654 // Search for the text in `mainWebView`.
655 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
659 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
660 findOnPageEditText.setOnKeyListener((v, keyCode, event) -> {
661 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
662 // Hide the soft keyboard. `0` indicates no additional flags.
663 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
665 // Consume the event.
667 } else { // A different key was pressed.
668 // Do not consume the event.
673 // Implement swipe to refresh
674 swipeRefreshLayout = findViewById(R.id.swipe_refreshlayout);
675 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
676 swipeRefreshLayout.setOnRefreshListener(() -> mainWebView.reload());
678 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
679 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
680 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
682 // Listen for touches on the navigation menu.
683 final NavigationView navigationView = findViewById(R.id.navigationview);
684 navigationView.setNavigationItemSelectedListener(this);
686 // 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.
687 final Menu navigationMenu = navigationView.getMenu();
688 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
689 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
690 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
692 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
693 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
694 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
696 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
697 currentBookmarksFolder = "";
699 // Load the home folder, which is `""` in the database.
700 loadBookmarksFolder();
702 bookmarksListView.setOnItemClickListener((parent, view, position, id) -> {
703 // Convert the id from long to int to match the format of the bookmarks database.
704 int databaseID = (int) id;
706 // Get the bookmark `Cursor` for this ID and move it to the first row.
707 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
708 bookmarkCursor.moveToFirst();
710 // Act upon the bookmark according to the type.
711 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
712 // Store the new folder name in `currentBookmarksFolder`.
713 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
715 // Load the new folder.
716 loadBookmarksFolder();
717 } else { // The selected bookmark is not a folder.
718 // Load the bookmark URL.
719 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
721 // Close the bookmarks drawer.
722 drawerLayout.closeDrawer(GravityCompat.END);
725 // Close the `Cursor`.
726 bookmarkCursor.close();
729 bookmarksListView.setOnItemLongClickListener((parent, view, position, id) -> {
730 // Convert the database ID from `long` to `int`.
731 int databaseId = (int) id;
733 // Find out if the selected bookmark is a folder.
734 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
737 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
738 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
740 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
741 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
742 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
744 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
745 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
746 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
749 // Consume the event.
753 // The `DrawerListener` allows us to update the Navigation Menu.
754 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
756 public void onDrawerSlide(View drawerView, float slideOffset) {
760 public void onDrawerOpened(View drawerView) {
764 public void onDrawerClosed(View drawerView) {
768 public void onDrawerStateChanged(int newState) {
769 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
770 // Update the `Back`, `Forward`, and `History` menu items.
771 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
772 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
773 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
775 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
776 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
778 // Clear the focus from `urlTextBox` if it has it.
779 urlTextBox.clearFocus();
784 // drawerToggle creates the hamburger icon at the start of the AppBar.
785 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
787 // Initialize `adServerSet`.
788 final Set<String> adServersSet = new HashSet<>();
790 // Load the list of ad servers into memory.
792 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
793 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
795 // Create a string for storing each ad server.
798 // Populate `adServersSet`.
799 while ((adServer = bufferedReader.readLine()) != null) {
800 adServersSet.add(adServer);
803 // Close `bufferedReader`.
804 bufferedReader.close();
805 } catch (IOException ioException) {
806 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
809 mainWebView.setWebViewClient(new WebViewClient() {
810 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
811 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
812 @SuppressWarnings("deprecation")
814 public boolean shouldOverrideUrlLoading(WebView view, String url) {
815 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
816 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
817 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
819 // Parse the url and set it as the data for the `Intent`.
820 emailIntent.setData(Uri.parse(url));
822 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
823 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
826 startActivity(emailIntent);
828 // Returning `true` indicates the application is handling the URL.
830 } else { // Load the URL in Privacy Browser.
831 // Apply the domain settings for the new URL.
832 applyDomainSettings(url);
834 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
839 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
840 @SuppressWarnings("deprecation")
842 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
843 if (adBlockerEnabled) { // Block ads.
844 // Extract the host from `url`.
845 Uri requestUri = Uri.parse(url);
846 String requestHost = requestUri.getHost();
848 // Initialize a variable to track if this is an ad server.
849 boolean requestHostIsAdServer = false;
851 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
852 if (requestHost != null) {
853 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
854 if (adServersSet.contains(requestHost)) {
855 requestHostIsAdServer = true;
858 // Strip out the lowest subdomain of `requestHost`.
859 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
863 if (requestHostIsAdServer) { // It is an ad server.
864 // Return an empty `WebResourceResponse`.
865 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
866 } else { // It is not an ad server.
867 // `return null` loads the requested resource.
870 } else { // Ad blocking is disabled.
871 // `return null` loads the requested resource.
876 // Handle HTTP authentication requests.
878 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
879 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
880 httpAuthHandler = handler;
882 // Display the HTTP authentication dialog.
883 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
884 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
887 // Update the URL in urlTextBox when the page starts to load.
889 public void onPageStarted(WebView view, String url, Bitmap favicon) {
890 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
892 mainWebView.setVisibility(View.INVISIBLE);
895 // Hide the keyboard. `0` indicates no additional flags.
896 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
898 // Check to see if we are waiting on Orbot.
899 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
900 // 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.
901 formattedUrlString = url;
903 // Display the formatted URL text.
904 urlTextBox.setText(formattedUrlString);
906 // Apply text highlighting to `urlTextBox`.
909 // Apply any custom domain settings if the URL was loaded by navigating history.
910 if (navigatingHistory) {
911 applyDomainSettings(url);
914 // 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.
919 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
921 public void onPageFinished(WebView view, String url) {
922 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
923 urlIsLoading = false;
925 // Clear the cache and history if Incognito Mode is enabled.
926 if (incognitoModeEnabled) {
927 // Clear the cache. `true` includes disk files.
928 mainWebView.clearCache(true);
930 // Clear the back/forward history.
931 mainWebView.clearHistory();
933 // Manually delete cache folders.
935 // Delete the main `cache` folder.
936 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
938 // 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`.
939 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
940 } catch (IOException e) {
941 // Do nothing if an error is thrown.
945 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
946 if (!waitingForOrbot) {
947 // Check to see if `WebView` has set `url` to be `about:blank`.
948 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
949 // Set `formattedUrlString` to `""`.
950 formattedUrlString = "";
952 urlTextBox.setText(formattedUrlString);
954 // Request focus for `urlTextBox`.
955 urlTextBox.requestFocus();
957 // Display the keyboard.
958 inputMethodManager.showSoftInput(urlTextBox, 0);
960 // Apply the domain settings. This clears any settings from the previous domain.
961 applyDomainSettings(formattedUrlString);
962 } else { // `WebView` has loaded a webpage.
963 // Set `formattedUrlString`.
964 formattedUrlString = url;
966 // Only update `urlTextBox` if the user is not typing in it.
967 if (!urlTextBox.hasFocus()) {
968 // Display the formatted URL text.
969 urlTextBox.setText(formattedUrlString);
971 // Apply text highlighting to `urlTextBox`.
976 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
977 sslCertificate = mainWebView.getCertificate();
979 // 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.
980 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
981 // Initialize the current SSL certificate variables.
982 String currentWebsiteIssuedToCName = "";
983 String currentWebsiteIssuedToOName = "";
984 String currentWebsiteIssuedToUName = "";
985 String currentWebsiteIssuedByCName = "";
986 String currentWebsiteIssuedByOName = "";
987 String currentWebsiteIssuedByUName = "";
988 Date currentWebsiteSslStartDate = null;
989 Date currentWebsiteSslEndDate = null;
992 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
993 if (sslCertificate != null) {
994 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
995 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
996 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
997 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
998 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
999 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1000 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1001 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1004 // 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`.
1005 String currentWebsiteSslStartDateString = "";
1006 String currentWebsiteSslEndDateString = "";
1007 String pinnedDomainSslStartDateString = "";
1008 String pinnedDomainSslEndDateString = "";
1010 // Convert the `Dates` to `Strings` if they are not `null`.
1011 if (currentWebsiteSslStartDate != null) {
1012 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1015 if (currentWebsiteSslEndDate != null) {
1016 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1019 if (pinnedDomainSslStartDate != null) {
1020 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1023 if (pinnedDomainSslEndDate != null) {
1024 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1027 // Check to see if the pinned SSL certificate matches the current website certificate.
1028 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) || !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) ||
1029 !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) || !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1030 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) { // The pinned SSL certificate doesn't match the current domain certificate.
1031 //Display the pinned SSL certificate mismatch `AlertDialog`.
1032 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1033 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1039 // Handle SSL Certificate errors.
1041 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1042 // Get the current website SSL certificate.
1043 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1045 // Extract the individual pieces of information from the current website SSL certificate.
1046 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1047 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1048 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1049 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1050 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1051 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1052 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1053 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1055 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1056 if (pinnedDomainSslCertificate &&
1057 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) && currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) &&
1058 currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) && currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1059 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) { // An SSL certificate is pinned and matches the current domain certificate.
1060 // Proceed to the website without displaying an error.
1062 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1063 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1064 sslErrorHandler = handler;
1066 // Display the SSL error `AlertDialog`.
1067 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1068 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1073 // Get a handle for the progress bar.
1074 final ProgressBar progressBar = findViewById(R.id.progress_bar);
1076 mainWebView.setWebChromeClient(new WebChromeClient() {
1077 // Update the progress bar when a page is loading.
1079 public void onProgressChanged(WebView view, int progress) {
1080 // Inject the night mode CSS if night mode is enabled.
1082 // `background-color: #212121` sets the background to be dark gray. `color: #BDBDBD` sets the text color to be light gray. `box-shadow: none` removes a lower underline on links used by WordPress.
1083 // `text-decoration: none` removes all text underlines. `text-shadow: none` removes text shadows, which usually have a hard coded color. `border: none` removes all borders, which can also be used to underline text.
1084 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
1085 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '" +
1086 "* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important; text-shadow: none !important; border: none !important;}" +
1087 "a {color: #1565C0 !important;}" +
1088 "'; parent.appendChild(style)})()", value -> {
1089 // Initialize a `Handler` to display `mainWebView`.
1090 Handler displayWebViewHandler = new Handler();
1092 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
1093 Runnable displayWebViewRunnable = () -> {
1094 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
1095 if (progressBar.getVisibility() == View.GONE) {
1096 mainWebView.setVisibility(View.VISIBLE);
1100 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
1101 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
1105 progressBar.setProgress(progress);
1106 if (progress < 100) {
1107 // Show the progress bar.
1108 progressBar.setVisibility(View.VISIBLE);
1110 // Hide the progress bar.
1111 progressBar.setVisibility(View.GONE);
1113 // Display `mainWebView` if night mode is disabled.
1114 // Because of a race condition between `applyDomainSettings` and `onPageStarted`, when night mode is set by domain settings the `WebView` may be hidden even if night mode is not currently enabled.
1116 mainWebView.setVisibility(View.VISIBLE);
1119 //Stop the `SwipeToRefresh` indicator if it is running
1120 swipeRefreshLayout.setRefreshing(false);
1124 // Set the favorite icon when it changes.
1126 public void onReceivedIcon(WebView view, Bitmap icon) {
1127 // Only update the favorite icon if the website has finished loading.
1128 if (progressBar.getVisibility() == View.GONE) {
1129 // Save a copy of the favorite icon.
1130 favoriteIconBitmap = icon;
1132 // Place the favorite icon in the appBar.
1133 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1137 // Save a copy of the title when it changes.
1139 public void onReceivedTitle(WebView view, String title) {
1140 // Save a copy of the title.
1141 webViewTitle = title;
1144 // Enter full screen video
1146 public void onShowCustomView(View view, CustomViewCallback callback) {
1147 // Pause the ad if this is the free flavor.
1148 if (BuildConfig.FLAVOR.contentEquals("free")) {
1149 BannerAd.pauseAd(adView);
1152 // Remove the translucent overlays.
1153 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1155 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1156 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1158 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1159 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1160 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1162 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1164 // Set `rootCoordinatorLayout` to fill the entire screen.
1165 rootCoordinatorLayout.setFitsSystemWindows(false);
1167 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1168 fullScreenVideoFrameLayout.addView(view);
1169 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1172 // Exit full screen video
1173 public void onHideCustomView() {
1174 // Hide `fullScreenVideoFrameLayout`.
1175 fullScreenVideoFrameLayout.removeAllViews();
1176 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1178 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1179 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1181 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1182 rootCoordinatorLayout.setFitsSystemWindows(true);
1184 // Show the ad if this is the free flavor.
1185 if (BuildConfig.FLAVOR.contentEquals("free")) {
1186 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1187 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1189 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1190 adView = findViewById(R.id.adview);
1195 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1196 registerForContextMenu(mainWebView);
1198 // Allow the downloading of files.
1199 mainWebView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
1200 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1201 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1202 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1205 // Allow pinch to zoom.
1206 mainWebView.getSettings().setBuiltInZoomControls(true);
1208 // Hide zoom controls.
1209 mainWebView.getSettings().setDisplayZoomControls(false);
1211 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1212 mainWebView.getSettings().setUseWideViewPort(true);
1214 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1215 mainWebView.getSettings().setLoadWithOverviewMode(true);
1217 // Explicitly disable geolocation.
1218 mainWebView.getSettings().setGeolocationEnabled(false);
1220 // Initialize cookieManager.
1221 cookieManager = CookieManager.getInstance();
1223 // 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).
1224 customHeaders.put("X-Requested-With", "");
1226 // 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.
1227 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1229 // Get the intent that started the app.
1230 final Intent launchingIntent = getIntent();
1232 // Extract the launching intent data as `launchingIntentUriData`.
1233 final Uri launchingIntentUriData = launchingIntent.getData();
1235 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1236 if (launchingIntentUriData != null) {
1237 formattedUrlString = launchingIntentUriData.toString();
1240 // Get a handle for the `Runtime`.
1241 privacyBrowserRuntime = Runtime.getRuntime();
1243 // Store the application's private data directory.
1244 privateDataDirectoryString = getApplicationInfo().dataDir; // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1246 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1247 inFullScreenBrowsingMode = false;
1249 // Initialize AdView for the free flavor.
1250 adView = findViewById(R.id.adview);
1252 // Initialize the privacy settings variables.
1253 javaScriptEnabled = false;
1254 firstPartyCookiesEnabled = false;
1255 thirdPartyCookiesEnabled = false;
1256 domStorageEnabled = false;
1257 saveFormDataEnabled = false;
1260 // Initialize `webViewTitle`.
1261 webViewTitle = getString(R.string.no_title);
1263 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1264 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1265 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1266 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1268 // If the favorite icon is null, load the default.
1269 if (favoriteIconBitmap == null) {
1270 favoriteIconBitmap = favoriteIconDefaultBitmap;
1273 // Apply the app settings from the shared preferences.
1276 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1277 if (!waitingForOrbot) {
1278 loadUrl(formattedUrlString);
1283 protected void onNewIntent(Intent intent) {
1284 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1287 if (intent.getData() != null) {
1288 // Get the intent data and convert it to a string.
1289 final Uri intentUriData = intent.getData();
1290 formattedUrlString = intentUriData.toString();
1293 // Close the navigation drawer if it is open.
1294 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1295 drawerLayout.closeDrawer(GravityCompat.START);
1298 // Load the website.
1299 loadUrl(formattedUrlString);
1301 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1302 mainWebView.requestFocus();
1306 public void onRestart() {
1309 // Apply the app settings, which may have been changed in `SettingsActivity`.
1312 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1313 updatePrivacyIcons(true);
1315 // Set the display webpage images mode.
1316 setDisplayWebpageImages();
1318 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1319 if (reloadOnRestart) {
1320 // Reload `mainWebView`.
1321 mainWebView.reload();
1323 // Reset `reloadOnRestartBoolean`.
1324 reloadOnRestart = false;
1327 // Load the URL on restart to apply changes to night mode.
1328 if (loadUrlOnRestart) {
1329 // Load the current `formattedUrlString`.
1330 loadUrl(formattedUrlString);
1332 // Reset `loadUrlOnRestart.
1333 loadUrlOnRestart = false;
1337 if (restartFromBookmarksActivity) {
1338 // Close the bookmarks drawer.
1339 drawerLayout.closeDrawer(GravityCompat.END);
1341 // Reload the bookmarks drawer.
1342 loadBookmarksFolder();
1344 // Reset `restartFromBookmarksActivity`.
1345 restartFromBookmarksActivity = false;
1349 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1351 public void onResume() {
1354 // Resume JavaScript (if enabled).
1355 mainWebView.resumeTimers();
1357 // Resume `mainWebView`.
1358 mainWebView.onResume();
1360 // Resume the adView for the free flavor.
1361 if (BuildConfig.FLAVOR.contentEquals("free")) {
1362 BannerAd.resumeAd(adView);
1367 public void onPause() {
1368 // Pause `mainWebView`.
1369 mainWebView.onPause();
1371 // Stop all JavaScript.
1372 mainWebView.pauseTimers();
1374 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1375 if (BuildConfig.FLAVOR.contentEquals("free")) {
1376 BannerAd.pauseAd(adView);
1383 public boolean onCreateOptionsMenu(Menu menu) {
1384 // Inflate the menu; this adds items to the action bar if it is present.
1385 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1387 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1390 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1391 updatePrivacyIcons(false);
1393 // Get handles for the menu items.
1394 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1395 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1396 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1397 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1399 // Only display third-party cookies if SDK >= 21
1400 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1402 // Get the shared preference values. `this` references the current context.
1403 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1405 // Set the status of the additional app bar icons. The default is `false`.
1406 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1407 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1408 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1409 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1410 } else { //Do not display the additional icons.
1411 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1412 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1413 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1420 public boolean onPrepareOptionsMenu(Menu menu) {
1421 // Get handles for the menu items.
1422 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1423 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1424 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1425 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1426 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1427 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1428 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1429 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1430 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1431 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1433 // Set the status of the menu item checkboxes.
1434 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1435 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1436 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1437 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1438 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1440 // Enable third-party cookies if first-party cookies are enabled.
1441 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1443 // Enable `DOM Storage` if JavaScript is enabled.
1444 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1446 // Enable `Clear Cookies` if there are any.
1447 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1449 // Get a count of the number of files in the `Local Storage` directory.
1450 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1451 int localStorageDirectoryNumberOfFiles = 0;
1452 if (localStorageDirectory.exists()) {
1453 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1456 // Get a count of the number of files in the `IndexedDB` directory.
1457 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1458 int indexedDBDirectoryNumberOfFiles = 0;
1459 if (indexedDBDirectory.exists()) {
1460 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1463 // Enable `Clear DOM Storage` if there is any.
1464 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1466 // Enable `Clear Form Data` is there is any.
1467 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1468 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1470 // Initialize font size variables.
1471 int fontSize = mainWebView.getSettings().getTextZoom();
1472 String fontSizeTitle;
1473 MenuItem selectedFontSizeMenuItem;
1475 // Prepare the font size title and current size menu item.
1478 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1479 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1483 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1484 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1488 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1489 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1493 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1494 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1498 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1499 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1503 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1504 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1508 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1509 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1513 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1514 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1518 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1519 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1523 // Set the font size title and select the current size menu item.
1524 fontSizeMenuItem.setTitle(fontSizeTitle);
1525 selectedFontSizeMenuItem.setChecked(true);
1527 // Only show `Refresh` if `swipeToRefresh` is disabled.
1528 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1530 // Run all the other default commands.
1531 super.onPrepareOptionsMenu(menu);
1533 // `return true` displays the menu.
1538 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1539 @SuppressLint("SetJavaScriptEnabled")
1540 // removeAllCookies is deprecated, but it is required for API < 21.
1541 @SuppressWarnings("deprecation")
1542 public boolean onOptionsItemSelected(MenuItem menuItem) {
1543 int menuItemId = menuItem.getItemId();
1545 // Set the commands that relate to the menu entries.
1546 switch (menuItemId) {
1547 case R.id.toggle_javascript:
1548 // Switch the status of javaScriptEnabled.
1549 javaScriptEnabled = !javaScriptEnabled;
1551 // Apply the new JavaScript status.
1552 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1554 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1555 updatePrivacyIcons(true);
1557 // Display a `Snackbar`.
1558 if (javaScriptEnabled) { // JavaScrip is enabled.
1559 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1560 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1561 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1562 } else { // Privacy mode.
1563 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1566 // Reload the WebView.
1567 mainWebView.reload();
1570 case R.id.toggle_first_party_cookies:
1571 // Switch the status of firstPartyCookiesEnabled.
1572 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1574 // Update the menu checkbox.
1575 menuItem.setChecked(firstPartyCookiesEnabled);
1577 // Apply the new cookie status.
1578 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1580 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1581 updatePrivacyIcons(true);
1583 // Display a `Snackbar`.
1584 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1585 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1586 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1587 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1588 } else { // Privacy mode.
1589 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1592 // Reload the WebView.
1593 mainWebView.reload();
1596 case R.id.toggle_third_party_cookies:
1597 if (Build.VERSION.SDK_INT >= 21) {
1598 // Switch the status of thirdPartyCookiesEnabled.
1599 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1601 // Update the menu checkbox.
1602 menuItem.setChecked(thirdPartyCookiesEnabled);
1604 // Apply the new cookie status.
1605 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1607 // Display a `Snackbar`.
1608 if (thirdPartyCookiesEnabled) {
1609 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1611 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1614 // Reload the WebView.
1615 mainWebView.reload();
1616 } // Else do nothing because SDK < 21.
1619 case R.id.toggle_dom_storage:
1620 // Switch the status of domStorageEnabled.
1621 domStorageEnabled = !domStorageEnabled;
1623 // Update the menu checkbox.
1624 menuItem.setChecked(domStorageEnabled);
1626 // Apply the new DOM Storage status.
1627 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1629 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1630 updatePrivacyIcons(true);
1632 // Display a `Snackbar`.
1633 if (domStorageEnabled) {
1634 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1636 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1639 // Reload the WebView.
1640 mainWebView.reload();
1643 case R.id.toggle_save_form_data:
1644 // Switch the status of saveFormDataEnabled.
1645 saveFormDataEnabled = !saveFormDataEnabled;
1647 // Update the menu checkbox.
1648 menuItem.setChecked(saveFormDataEnabled);
1650 // Apply the new form data status.
1651 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1653 // Display a `Snackbar`.
1654 if (saveFormDataEnabled) {
1655 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1657 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1660 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1661 updatePrivacyIcons(true);
1663 // Reload the WebView.
1664 mainWebView.reload();
1667 case R.id.clear_cookies:
1668 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1669 .setAction(R.string.undo, v -> {
1670 // Do nothing because everything will be handled by `onDismissed()` below.
1672 .addCallback(new Snackbar.Callback() {
1674 public void onDismissed(Snackbar snackbar, int event) {
1676 // The user pushed the `Undo` button.
1677 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1681 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1683 // `cookieManager.removeAllCookie()` varies by SDK.
1684 if (Build.VERSION.SDK_INT < 21) {
1685 cookieManager.removeAllCookie();
1687 // `null` indicates no callback.
1688 cookieManager.removeAllCookies(null);
1696 case R.id.clear_dom_storage:
1697 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1698 .setAction(R.string.undo, v -> {
1699 // Do nothing because everything will be handled by `onDismissed()` below.
1701 .addCallback(new Snackbar.Callback() {
1703 public void onDismissed(Snackbar snackbar, int event) {
1705 // The user pushed the `Undo` button.
1706 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1710 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1712 // Delete the DOM Storage.
1713 WebStorage webStorage = WebStorage.getInstance();
1714 webStorage.deleteAllData();
1716 // Manually remove `IndexedDB` if it exists.
1718 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1719 } catch (IOException e) {
1720 // Do nothing if an error is thrown.
1728 case R.id.clear_form_data:
1729 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1730 .setAction(R.string.undo, v -> {
1731 // Do nothing because everything will be handled by `onDismissed()` below.
1733 .addCallback(new Snackbar.Callback() {
1735 public void onDismissed(Snackbar snackbar, int event) {
1737 // The user pushed the `Undo` button.
1738 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1742 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1744 // Delete the form data.
1745 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1746 mainWebViewDatabase.clearFormData();
1753 case R.id.font_size_twenty_five_percent:
1754 mainWebView.getSettings().setTextZoom(25);
1757 case R.id.font_size_fifty_percent:
1758 mainWebView.getSettings().setTextZoom(50);
1761 case R.id.font_size_seventy_five_percent:
1762 mainWebView.getSettings().setTextZoom(75);
1765 case R.id.font_size_one_hundred_percent:
1766 mainWebView.getSettings().setTextZoom(100);
1769 case R.id.font_size_one_hundred_twenty_five_percent:
1770 mainWebView.getSettings().setTextZoom(125);
1773 case R.id.font_size_one_hundred_fifty_percent:
1774 mainWebView.getSettings().setTextZoom(150);
1777 case R.id.font_size_one_hundred_seventy_five_percent:
1778 mainWebView.getSettings().setTextZoom(175);
1781 case R.id.font_size_two_hundred_percent:
1782 mainWebView.getSettings().setTextZoom(200);
1785 case R.id.display_images:
1786 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1787 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1788 mainWebView.reload();
1789 } else { // Images are not currently loaded automatically.
1790 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1793 // Set `onTheFlyDisplayImagesSet`.
1794 onTheFlyDisplayImagesSet = true;
1798 // Setup the share string.
1799 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1801 // Create the share intent.
1802 Intent shareIntent = new Intent();
1803 shareIntent.setAction(Intent.ACTION_SEND);
1804 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1805 shareIntent.setType("text/plain");
1808 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1811 case R.id.find_on_page:
1812 // Hide the URL app bar.
1813 supportAppBar.setVisibility(View.GONE);
1815 // Show the Find on Page `RelativeLayout`.
1816 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1818 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android. http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1819 findOnPageEditText.postDelayed(() -> {
1820 // Set the focus on `findOnPageEditText`.
1821 findOnPageEditText.requestFocus();
1823 // Display the keyboard. `0` sets no input flags.
1824 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1829 // Get a `PrintManager` instance.
1830 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1832 // Convert `mainWebView` to `printDocumentAdapter`.
1833 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1835 // Remove the lint error below that `printManager` might be `null`.
1836 assert printManager != null;
1838 // Print the document. The print attributes are `null`.
1839 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1842 case R.id.add_to_homescreen:
1843 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1844 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1845 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1847 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1851 mainWebView.reload();
1855 // Don't consume the event.
1856 return super.onOptionsItemSelected(menuItem);
1860 // removeAllCookies is deprecated, but it is required for API < 21.
1861 @SuppressWarnings("deprecation")
1863 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1864 int menuItemId = menuItem.getItemId();
1866 switch (menuItemId) {
1872 if (mainWebView.canGoBack()) {
1873 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1874 navigatingHistory = true;
1876 // Load the previous website in the history.
1877 mainWebView.goBack();
1882 if (mainWebView.canGoForward()) {
1883 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1884 navigatingHistory = true;
1886 // Load the next website in the history.
1887 mainWebView.goForward();
1892 // Get the `WebBackForwardList`.
1893 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1895 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1896 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1897 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1900 case R.id.downloads:
1901 // Launch the system Download Manager.
1902 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1904 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1905 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1907 startActivity(downloadManagerIntent);
1911 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1912 currentDomainName = "";
1914 // Launch `DomainsActivity`.
1915 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1916 startActivity(domainsIntent);
1920 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1921 currentDomainName = "";
1923 // Launch `SettingsActivity`.
1924 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1925 startActivity(settingsIntent);
1929 // Launch `GuideActivity`.
1930 Intent guideIntent = new Intent(this, GuideActivity.class);
1931 startActivity(guideIntent);
1935 // Launch `AboutActivity`.
1936 Intent aboutIntent = new Intent(this, AboutActivity.class);
1937 startActivity(aboutIntent);
1940 case R.id.clearAndExit:
1941 // Get a handle for `sharedPreferences`. `this` references the current context.
1942 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1944 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1947 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1948 // The command to remove cookies changed slightly in API 21.
1949 if (Build.VERSION.SDK_INT >= 21) {
1950 cookieManager.removeAllCookies(null);
1952 cookieManager.removeAllCookie();
1955 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1957 // We have to use two commands because `Runtime.exec()` does not like `*`.
1958 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1959 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1960 } catch (IOException e) {
1961 // Do nothing if an error is thrown.
1965 // Clear DOM storage.
1966 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1967 // Ask `WebStorage` to clear the DOM storage.
1968 WebStorage webStorage = WebStorage.getInstance();
1969 webStorage.deleteAllData();
1971 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1973 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1974 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1976 // We have to use multiple commands because `Runtime.exec()` does not like `*`.
1977 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1978 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1979 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1980 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1981 } catch (IOException e) {
1982 // Do nothing if an error is thrown.
1987 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1988 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1989 webViewDatabase.clearFormData();
1991 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1993 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1994 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1995 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1996 } catch (IOException e) {
1997 // Do nothing if an error is thrown.
2002 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2003 // `true` includes disk files.
2004 mainWebView.clearCache(true);
2006 // Manually delete the cache directories.
2008 // Delete the main cache directory.
2009 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2011 // Delete the secondary `Service Worker` cache directory. We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2012 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2013 } catch (IOException e) {
2014 // Do nothing if an error is thrown.
2018 // Clear SSL certificate preferences.
2019 mainWebView.clearSslPreferences();
2021 // Clear the back/forward history.
2022 mainWebView.clearHistory();
2024 // Clear `formattedUrlString`.
2025 formattedUrlString = null;
2027 // Clear `customHeaders`.
2028 customHeaders.clear();
2030 // Detach all views from `mainWebViewRelativeLayout`.
2031 mainWebViewRelativeLayout.removeAllViews();
2033 // Destroy the internal state of `mainWebView`.
2034 mainWebView.destroy();
2036 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2037 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2038 if (clearEverything) {
2040 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2041 } catch (IOException e) {
2042 // Do nothing if an error is thrown.
2046 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2047 if (Build.VERSION.SDK_INT >= 21) {
2048 finishAndRemoveTask();
2053 // Remove the terminated program from RAM. The status code is `0`.
2058 // Close the navigation drawer.
2059 drawerLayout.closeDrawer(GravityCompat.START);
2064 public void onPostCreate(Bundle savedInstanceState) {
2065 super.onPostCreate(savedInstanceState);
2067 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2068 drawerToggle.syncState();
2072 public void onConfigurationChanged(Configuration newConfig) {
2073 super.onConfigurationChanged(newConfig);
2075 // Reload the ad for the free flavor if we are not in full screen mode.
2076 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2078 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2080 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2081 adView = findViewById(R.id.adview);
2084 // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug: https://code.google.com/p/android/issues/detail?id=20493#c8
2085 // ActivityCompat.invalidateOptionsMenu(this);
2089 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2090 // Store the `HitTestResult`.
2091 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2094 final String imageUrl;
2095 final String linkUrl;
2097 // Get a handle for the `ClipboardManager`.
2098 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2100 // Remove the lint errors below that `clipboardManager` might be `null`.
2101 assert clipboardManager != null;
2103 switch (hitTestResult.getType()) {
2104 // `SRC_ANCHOR_TYPE` is a link.
2105 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2106 // Get the target URL.
2107 linkUrl = hitTestResult.getExtra();
2109 // Set the target URL as the title of the `ContextMenu`.
2110 menu.setHeaderTitle(linkUrl);
2112 // Add a `Load URL` entry.
2113 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
2118 // Add a `Copy URL` entry.
2119 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2120 // Save the link URL in a `ClipData`.
2121 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2123 // Set the `ClipData` as the clipboard's primary clip.
2124 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2128 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2129 menu.add(R.string.cancel);
2132 case WebView.HitTestResult.EMAIL_TYPE:
2133 // Get the target URL.
2134 linkUrl = hitTestResult.getExtra();
2136 // Set the target URL as the title of the `ContextMenu`.
2137 menu.setHeaderTitle(linkUrl);
2139 // Add a `Write Email` entry.
2140 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2141 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2142 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2144 // Parse the url and set it as the data for the `Intent`.
2145 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2147 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2148 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2151 startActivity(emailIntent);
2155 // Add a `Copy Email Address` entry.
2156 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2157 // Save the email address in a `ClipData`.
2158 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2160 // Set the `ClipData` as the clipboard's primary clip.
2161 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2165 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2166 menu.add(R.string.cancel);
2169 // `IMAGE_TYPE` is an image.
2170 case WebView.HitTestResult.IMAGE_TYPE:
2171 // Get the image URL.
2172 imageUrl = hitTestResult.getExtra();
2174 // Set the image URL as the title of the `ContextMenu`.
2175 menu.setHeaderTitle(imageUrl);
2177 // Add a `View Image` entry.
2178 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2183 // Add a `Download Image` entry.
2184 menu.add(R.string.download_image).setOnMenuItemClickListener(item -> {
2185 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2186 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2187 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2191 // Add a `Copy URL` entry.
2192 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2193 // Save the image URL in a `ClipData`.
2194 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2196 // Set the `ClipData` as the clipboard's primary clip.
2197 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2201 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2202 menu.add(R.string.cancel);
2206 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2207 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2208 // Get the image URL.
2209 imageUrl = hitTestResult.getExtra();
2211 // Set the image URL as the title of the `ContextMenu`.
2212 menu.setHeaderTitle(imageUrl);
2214 // Add a `View Image` entry.
2215 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2220 // Add a `Download Image` entry.
2221 menu.add(R.string.download_image).setOnMenuItemClickListener(item -> {
2222 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2223 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2224 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2228 // Add a `Copy URL` entry.
2229 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2230 // Save the image URL in a `ClipData`.
2231 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2233 // Set the `ClipData` as the clipboard's primary clip.
2234 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2238 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2239 menu.add(R.string.cancel);
2245 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2246 // Get the `EditTexts` from the `dialogFragment`.
2247 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2248 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2250 // Extract the strings from the `EditTexts`.
2251 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2252 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2254 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2255 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2256 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2257 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2259 // Display the new bookmark below the current items in the (0 indexed) list.
2260 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2262 // Create the bookmark.
2263 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2265 // Update `bookmarksCursor` with the current contents of this folder.
2266 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2268 // Update the `ListView`.
2269 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2271 // Scroll to the new bookmark.
2272 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2276 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2277 // Get handles for the views in `dialogFragment`.
2278 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2279 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2280 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2282 // Get new folder name string.
2283 String folderNameString = createFolderNameEditText.getText().toString();
2285 // Get the new folder icon `Bitmap`.
2286 Bitmap folderIconBitmap;
2287 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2288 // Get the default folder icon and convert it to a `Bitmap`.
2289 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2290 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2291 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2292 } else { // Use the `WebView` favorite icon.
2293 folderIconBitmap = favoriteIconBitmap;
2296 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2297 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2298 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2299 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2301 // Move all the bookmarks down one in the display order.
2302 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2303 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2304 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2307 // Create the folder, which will be placed at the top of the `ListView`.
2308 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2310 // Update `bookmarksCursor` with the current contents of this folder.
2311 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2313 // Update the `ListView`.
2314 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2316 // Scroll to the new folder.
2317 bookmarksListView.setSelection(0);
2321 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2322 // Get shortcutNameEditText from the alert dialog.
2323 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2325 // Create the bookmark shortcut based on formattedUrlString.
2326 Intent bookmarkShortcut = new Intent();
2327 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
2328 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
2330 // Place the bookmark shortcut on the home screen.
2331 Intent placeBookmarkShortcut = new Intent();
2332 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
2333 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
2334 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
2335 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
2336 sendBroadcast(placeBookmarkShortcut);
2340 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2341 // Download the image if it has an HTTP or HTTPS URI.
2342 if (imageUrl.startsWith("http")) {
2343 // Get a handle for the system `DOWNLOAD_SERVICE`.
2344 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2346 // Parse `imageUrl`.
2347 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2349 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2350 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2351 if (firstPartyCookiesEnabled) {
2352 // Get the cookies for `imageUrl`.
2353 String cookies = cookieManager.getCookie(imageUrl);
2355 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2356 downloadRequest.addRequestHeader("Cookie", cookies);
2359 // Get the file name from `dialogFragment`.
2360 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2361 String imageName = downloadImageNameEditText.getText().toString();
2363 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2364 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2365 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2366 } else { // Only set the title using `imageName`.
2367 downloadRequest.setTitle(imageName);
2370 // Allow `MediaScanner` to index the download if it is a media file.
2371 downloadRequest.allowScanningByMediaScanner();
2373 // Add the URL as the description for the download.
2374 downloadRequest.setDescription(imageUrl);
2376 // Show the download notification after the download is completed.
2377 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2379 // Remove the lint warning below that `downloadManager` might be `null`.
2380 assert downloadManager != null;
2382 // Initiate the download.
2383 downloadManager.enqueue(downloadRequest);
2384 } else { // The image is not an HTTP or HTTPS URI.
2385 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2390 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2391 // Download the file if it has an HTTP or HTTPS URI.
2392 if (downloadUrl.startsWith("http")) {
2394 // Get a handle for the system `DOWNLOAD_SERVICE`.
2395 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2397 // Parse `downloadUrl`.
2398 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2400 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2401 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2402 if (firstPartyCookiesEnabled) {
2403 // Get the cookies for `downloadUrl`.
2404 String cookies = cookieManager.getCookie(downloadUrl);
2406 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2407 downloadRequest.addRequestHeader("Cookie", cookies);
2410 // Get the file name from `dialogFragment`.
2411 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2412 String fileName = downloadFileNameEditText.getText().toString();
2414 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2415 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2416 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2417 } else { // Only set the title using `fileName`.
2418 downloadRequest.setTitle(fileName);
2421 // Allow `MediaScanner` to index the download if it is a media file.
2422 downloadRequest.allowScanningByMediaScanner();
2424 // Add the URL as the description for the download.
2425 downloadRequest.setDescription(downloadUrl);
2427 // Show the download notification after the download is completed.
2428 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2430 // Remove the lint warning below that `downloadManager` might be `null`.
2431 assert downloadManager != null;
2433 // Initiate the download.
2434 downloadManager.enqueue(downloadRequest);
2435 } else { // The download is not an HTTP or HTTPS URI.
2436 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2441 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2442 // Get handles for the views from `dialogFragment`.
2443 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2444 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2445 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2447 // Store the bookmark strings.
2448 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2449 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2451 // Update the bookmark.
2452 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2453 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2454 } else { // Update the bookmark using the `WebView` favorite icon.
2455 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2456 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2457 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2458 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2460 // Update the bookmark and the favorite icon.
2461 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2464 // Update `bookmarksCursor` with the current contents of this folder.
2465 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2467 // Update the `ListView`.
2468 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2472 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2473 // Get handles for the views from `dialogFragment`.
2474 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2475 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2476 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2477 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2479 // Get the new folder name.
2480 String newFolderNameString = editFolderNameEditText.getText().toString();
2482 // Check if the favorite icon has changed.
2483 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2484 // Update the name in the database.
2485 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2486 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2487 // Get the new folder icon `Bitmap`.
2488 Bitmap folderIconBitmap;
2489 if (defaultFolderIconRadioButton.isChecked()) {
2490 // Get the default folder icon and convert it to a `Bitmap`.
2491 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2492 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2493 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2494 } else { // Use the `WebView` favorite icon.
2495 folderIconBitmap = favoriteIconBitmap;
2498 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2499 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2500 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2501 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2503 // Update the folder icon in the database.
2504 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2505 } else { // The folder icon and the name have changed.
2506 // Get the new folder icon `Bitmap`.
2507 Bitmap folderIconBitmap;
2508 if (defaultFolderIconRadioButton.isChecked()) {
2509 // Get the default folder icon and convert it to a `Bitmap`.
2510 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2511 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2512 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2513 } else { // Use the `WebView` favorite icon.
2514 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2517 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2518 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2519 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2520 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2522 // Update the folder name and icon in the database.
2523 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2526 // Update `bookmarksCursor` with the current contents of this folder.
2527 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2529 // Update the `ListView`.
2530 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2534 public void onHttpAuthenticationCancel() {
2535 // Cancel the `HttpAuthHandler`.
2536 httpAuthHandler.cancel();
2540 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2541 // Get handles for the `EditTexts`.
2542 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2543 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2545 // Proceed with the HTTP authentication.
2546 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2549 public void viewSslCertificate(View view) {
2550 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2551 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2552 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2556 public void onSslErrorCancel() {
2557 sslErrorHandler.cancel();
2561 public void onSslErrorProceed() {
2562 sslErrorHandler.proceed();
2566 public void onSslMismatchBack() {
2567 if (mainWebView.canGoBack()) { // There is a back page in the history.
2568 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2569 navigatingHistory = true;
2572 mainWebView.goBack();
2573 } else { // There are no pages to go back to.
2574 // Load a blank page
2580 public void onSslMismatchProceed() {
2581 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2582 ignorePinnedSslCertificate = true;
2586 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2587 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2588 navigatingHistory = true;
2590 // Load the history entry.
2591 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2595 public void onClearHistory() {
2596 // Clear the history.
2597 mainWebView.clearHistory();
2600 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2602 public void onBackPressed() {
2603 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2604 // Close the navigation drawer.
2605 drawerLayout.closeDrawer(GravityCompat.START);
2606 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2607 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2608 // close the bookmarks drawer.
2609 drawerLayout.closeDrawer(GravityCompat.END);
2610 } else { // A subfolder is displayed.
2611 // Place the former parent folder in `currentFolder`.
2612 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2614 // Load the new folder.
2615 loadBookmarksFolder();
2618 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2619 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2620 navigatingHistory = true;
2623 mainWebView.goBack();
2624 } else { // There isn't anything to do in Privacy Browser.
2625 // Pass `onBackPressed()` to the system.
2626 super.onBackPressed();
2630 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2631 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2632 String unformattedUrlString = urlTextBox.getText().toString().trim();
2634 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2635 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2636 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2637 if (!unformattedUrlString.startsWith("http")) {
2638 unformattedUrlString = "http://" + unformattedUrlString;
2641 // Initialize `unformattedUrl`.
2642 URL unformattedUrl = null;
2644 // 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.
2646 unformattedUrl = new URL(unformattedUrlString);
2647 } catch (MalformedURLException e) {
2648 e.printStackTrace();
2651 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2652 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2653 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2654 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2655 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2656 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2659 Uri.Builder formattedUri = new Uri.Builder();
2660 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2662 // Decode `formattedUri` as a `String` in `UTF-8`.
2663 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2665 // Sanitize the search input and convert it to a search.
2666 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2668 // Add the base search URL.
2669 formattedUrlString = searchURL + encodedUrlString;
2672 loadUrl(formattedUrlString);
2676 private void loadUrl(String url) {
2677 // Apply any custom domain settings.
2678 applyDomainSettings(url);
2681 mainWebView.loadUrl(url, customHeaders);
2683 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2684 urlIsLoading = true;
2687 public void findPreviousOnPage(View view) {
2688 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2689 mainWebView.findNext(false);
2692 public void findNextOnPage(View view) {
2693 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2694 mainWebView.findNext(true);
2697 public void closeFindOnPage(View view) {
2698 // Delete the contents of `find_on_page_edittext`.
2699 findOnPageEditText.setText(null);
2701 // Clear the highlighted phrases.
2702 mainWebView.clearMatches();
2704 // Hide the Find on Page `RelativeLayout`.
2705 findOnPageLinearLayout.setVisibility(View.GONE);
2707 // Show the URL app bar.
2708 supportAppBar.setVisibility(View.VISIBLE);
2710 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2711 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2714 private void applyAppSettings() {
2715 // Get a handle for `sharedPreferences`. `this` references the current context.
2716 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2718 // Store the values from `sharedPreferences` in variables.
2719 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2720 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2721 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2722 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2723 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2724 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2725 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2726 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2727 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2728 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2729 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2730 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2731 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2732 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2733 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2735 // Set the homepage, search, and proxy options.
2736 if (proxyThroughOrbot) { // Set the Tor options.
2737 // Set `torHomepageString` as `homepage`.
2738 homepage = torHomepageString;
2740 // If formattedUrlString is null assign the homepage to it.
2741 if (formattedUrlString == null) {
2742 formattedUrlString = homepage;
2745 // Set the search URL.
2746 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2747 searchURL = torSearchCustomURLString;
2748 } else { // Use the string from the pre-built list.
2749 searchURL = torSearchString;
2752 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2753 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2755 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2757 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2759 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2762 // Display a message to the user if we are waiting on Orbot.
2763 if (!orbotStatus.equals("ON")) {
2764 // Set `waitingForOrbot`.
2765 waitingForOrbot = true;
2767 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2768 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2770 } else { // Set the non-Tor options.
2771 // Set `homepageString` as `homepage`.
2772 homepage = homepageString;
2774 // If formattedUrlString is null assign the homepage to it.
2775 if (formattedUrlString == null) {
2776 formattedUrlString = homepage;
2779 // Set the search URL.
2780 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2781 searchURL = searchCustomURLString;
2782 } else { // Use the string from the pre-built list.
2783 searchURL = searchString;
2786 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2787 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2789 // Set the default `appBar` background. `this` refers to the context.
2791 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2793 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2796 // Reset `waitingForOrbot.
2797 waitingForOrbot = false;
2800 // Set swipe to refresh.
2801 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2803 // Set Do Not Track status.
2804 if (doNotTrackEnabled) {
2805 customHeaders.put("DNT", "1");
2807 customHeaders.remove("DNT");
2810 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2811 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2812 if (hideSystemBarsOnFullscreen) { // Hide everything.
2813 // Remove the translucent navigation setting if it is currently flagged.
2814 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2816 // Remove the translucent status bar overlay.
2817 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2819 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2820 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2822 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2823 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2824 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2826 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2827 } else { // Hide everything except the status and navigation bars.
2828 // Add the translucent status flag if it is unset.
2829 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2831 if (translucentNavigationBarOnFullscreen) {
2832 // Set the navigation bar to be translucent.
2833 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2835 // Set the navigation bar to be black.
2836 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2839 } else { // Switch to normal viewing mode.
2840 // Reset `inFullScreenBrowsingMode` to `false`.
2841 inFullScreenBrowsingMode = false;
2843 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2844 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2848 // Show the `BannerAd` in the free flavor.
2849 if (BuildConfig.FLAVOR.contentEquals("free")) {
2850 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2851 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2853 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2854 adView = findViewById(R.id.adview);
2857 // Remove the translucent navigation bar flag if it is set.
2858 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2860 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2861 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2863 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2864 rootCoordinatorLayout.setSystemUiVisibility(0);
2866 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2867 rootCoordinatorLayout.setFitsSystemWindows(true);
2871 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2872 @SuppressWarnings("deprecation")
2873 private void applyDomainSettings(String url) {
2874 // Reset `navigatingHistory`.
2875 navigatingHistory = false;
2877 // Parse the URL into a URI.
2878 Uri uri = Uri.parse(url);
2880 // Extract the domain from `uri`.
2881 String hostName = uri.getHost();
2883 // Initialize `loadingNewDomainName`.
2884 boolean loadingNewDomainName;
2886 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2887 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2888 //noinspection SimplifiableIfStatement
2889 if ((hostName == null) || (currentDomainName == null)) {
2890 loadingNewDomainName = true;
2891 } else { // Determine if `hostName` equals `currentDomainName`.
2892 loadingNewDomainName = !hostName.equals(currentDomainName);
2895 // 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.
2896 if (loadingNewDomainName) {
2897 // Set the new `hostname` as the `currentDomainName`.
2898 currentDomainName = hostName;
2900 // Reset `ignorePinnedSslCertificate`.
2901 ignorePinnedSslCertificate = false;
2903 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2904 favoriteIconBitmap = favoriteIconDefaultBitmap;
2905 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2907 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2908 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2909 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2911 // Get a full cursor from `domainsDatabaseHelper`.
2912 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2914 // Initialize `domainSettingsSet`.
2915 Set<String> domainSettingsSet = new HashSet<>();
2917 // Get the domain name column index.
2918 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2920 // Populate `domainSettingsSet`.
2921 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2922 // Move `domainsCursor` to the current row.
2923 domainNameCursor.moveToPosition(i);
2925 // Store the domain name in `domainSettingsSet`.
2926 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2929 // Close `domainNameCursor.
2930 domainNameCursor.close();
2932 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2933 domainSettingsApplied = false;
2934 String domainNameInDatabase = null;
2936 // Check the hostname.
2937 if (domainSettingsSet.contains(hostName)) {
2938 domainSettingsApplied = true;
2939 domainNameInDatabase = hostName;
2942 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2943 if (hostName != null) {
2944 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2945 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2946 domainSettingsApplied = true;
2947 domainNameInDatabase = "*." + hostName;
2950 // Strip out the lowest subdomain of `host`.
2951 hostName = hostName.substring(hostName.indexOf(".") + 1);
2955 // Get a handle for the shared preference. `this` references the current context.
2956 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2958 // Store the general preference information.
2959 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2960 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2961 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2962 nightMode = sharedPreferences.getBoolean("night_mode", false);
2964 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2965 // Get a cursor for the current host and move it to the first position.
2966 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2967 currentHostDomainSettingsCursor.moveToFirst();
2969 // Get the settings from the cursor.
2970 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
2971 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2972 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2973 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2974 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2975 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2976 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2977 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2978 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2979 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
2980 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
2981 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
2982 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
2983 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
2984 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
2985 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
2986 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
2988 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
2989 switch (nightModeInt) {
2990 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
2994 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
2999 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3001 javaScriptEnabled = true;
3004 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3005 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3006 pinnedDomainSslStartDate = null;
3008 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3011 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3012 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3013 pinnedDomainSslEndDate = null;
3015 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3018 // Close `currentHostDomainSettingsCursor`.
3019 currentHostDomainSettingsCursor.close();
3021 // Apply the domain settings.
3022 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3023 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3024 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3025 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3027 // Apply the font size.
3028 if (fontSize == 0) { // Apply the default font size.
3029 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3030 } else { // Apply the specified font size.
3031 mainWebView.getSettings().setTextZoom(fontSize);
3034 // Set third-party cookies status if API >= 21.
3035 if (Build.VERSION.SDK_INT >= 21) {
3036 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3039 // Only set the user agent if the webpage is not currently loading. Otherwise, changing the user agent on redirects can cause the original website to reload. <https://redmine.stoutner.com/issues/160>
3040 if (!urlIsLoading) {
3041 switch (userAgentString) {
3042 case "System default user agent":
3043 // Set the user agent according to the system default.
3044 switch (defaultUserAgentString) {
3045 case "WebView default user agent":
3046 // Set the user agent to `""`, which uses the default value.
3047 mainWebView.getSettings().setUserAgentString("");
3050 case "Custom user agent":
3051 // Set the custom user agent.
3052 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3056 // Use the selected user agent.
3057 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3061 case "WebView default user agent":
3062 // Set the user agent to `""`, which uses the default value.
3063 mainWebView.getSettings().setUserAgentString("");
3067 // Use the selected user agent.
3068 mainWebView.getSettings().setUserAgentString(userAgentString);
3072 // 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.
3074 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3076 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3078 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3079 // Store the values from `sharedPreferences` in variables.
3080 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3081 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3082 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3083 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3084 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3086 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3088 javaScriptEnabled = true;
3091 // Apply the default settings.
3092 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3093 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3094 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3095 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3096 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3098 // Reset the pinned SSL certificate information.
3099 domainSettingsDatabaseId = -1;
3100 pinnedDomainSslCertificate = false;
3101 pinnedDomainSslIssuedToCNameString = "";
3102 pinnedDomainSslIssuedToONameString = "";
3103 pinnedDomainSslIssuedToUNameString = "";
3104 pinnedDomainSslIssuedByCNameString = "";
3105 pinnedDomainSslIssuedByONameString = "";
3106 pinnedDomainSslIssuedByUNameString = "";
3107 pinnedDomainSslStartDate = null;
3108 pinnedDomainSslEndDate = null;
3110 // Set third-party cookies status if API >= 21.
3111 if (Build.VERSION.SDK_INT >= 21) {
3112 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3115 // Only set the user agent if the webpage is not currently loading. Otherwise, changing the user agent on redirects can cause the original website to reload. <https://redmine.stoutner.com/issues/160>
3116 if (!urlIsLoading) {
3117 switch (defaultUserAgentString) {
3118 case "WebView default user agent":
3119 // Set the user agent to `""`, which uses the default value.
3120 mainWebView.getSettings().setUserAgentString("");
3123 case "Custom user agent":
3124 // Set the custom user agent.
3125 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3129 // Use the selected user agent.
3130 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3134 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3135 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3138 // Close `domainsDatabaseHelper`.
3139 domainsDatabaseHelper.close();
3141 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3142 onTheFlyDisplayImagesSet = false;
3143 setDisplayWebpageImages();
3145 // Update the privacy icons, but only if `mainMenu` has already been populated.
3146 if (mainMenu != null) {
3147 updatePrivacyIcons(true);
3152 private void setDisplayWebpageImages() {
3153 if (!onTheFlyDisplayImagesSet) {
3154 if (domainSettingsApplied) { // Custom domain settings are applied.
3155 switch (displayWebpageImagesInt) {
3156 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3157 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3160 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3161 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3164 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3165 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3168 } else { // Default settings are applied.
3169 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3174 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3175 // Get handles for the icons.
3176 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3177 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3178 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3179 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3181 // Update `privacyIcon`.
3182 if (javaScriptEnabled) { // JavaScript is enabled.
3183 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3184 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3185 privacyIconMenuItem.setIcon(R.drawable.warning);
3186 } else { // All the dangerous features are disabled.
3187 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3190 // Update `firstPartyCookiesIcon`.
3191 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3192 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3193 } else { // First-party cookies are disabled.
3195 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3197 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3201 // Update `domStorageIcon`.
3202 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3203 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3204 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3206 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3208 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3210 } else { // JavaScript is disabled, so DOM storage is ghosted.
3212 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3214 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3218 // Update `formDataIcon`.
3219 if (saveFormDataEnabled) { // Form data is enabled.
3220 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3221 } else { // Form data is disabled.
3223 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3225 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3229 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
3230 if (runInvalidateOptionsMenu) {
3231 ActivityCompat.invalidateOptionsMenu(this);
3235 private void highlightUrlText() {
3236 String urlString = urlTextBox.getText().toString();
3238 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
3239 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3240 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
3241 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3244 // Get the index of the `/` immediately after the domain name.
3245 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3247 // De-emphasize the text after the domain name.
3248 if (endOfDomainName > 0) {
3249 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3253 private void loadBookmarksFolder() {
3254 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3255 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3257 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3258 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3260 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3261 // Inflate the individual item layout. `false` does not attach it to the root.
3262 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3266 public void bindView(View view, Context context, Cursor cursor) {
3267 // Get handles for the views.
3268 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3269 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3271 // Get the favorite icon byte array from the `Cursor`.
3272 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3274 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3275 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3277 // Display the bitmap in `bookmarkFavoriteIcon`.
3278 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3280 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3281 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3282 bookmarkNameTextView.setText(bookmarkNameString);
3284 // Make the font bold for folders.
3285 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3286 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3287 } else { // Reset the font to default for normal bookmarks.
3288 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3293 // Populate the `ListView` with the adapter.
3294 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3296 // Set the bookmarks drawer title.
3297 if (currentBookmarksFolder.isEmpty()) {
3298 bookmarksTitleTextView.setText(R.string.bookmarks);
3300 bookmarksTitleTextView.setText(currentBookmarksFolder);