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 email address in an external email program.
816 // 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 if (url.startsWith("tel:")) { // Load the phone number in the dialer.
831 // `ACTION_DIAL` open the dialer and loads the phone number, but waits for the user to place the call.
832 Intent dialIntent = new Intent(Intent.ACTION_DIAL);
834 // Add the phone number to the intent.
835 dialIntent.setData(Uri.parse(url));
837 // `FLAG_ACTIVITY_NEW_TASK` opens the dialer in a new task instead as part of Privacy Browser.
838 dialIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
841 startActivity(dialIntent);
843 // Returning `true` indicates the application is handling the URL.
845 } else { // Load the URL in Privacy Browser.
846 // Apply the domain settings for the new URL.
847 applyDomainSettings(url);
849 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
854 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
855 @SuppressWarnings("deprecation")
857 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
858 if (adBlockerEnabled) { // Block ads.
859 // Extract the host from `url`.
860 Uri requestUri = Uri.parse(url);
861 String requestHost = requestUri.getHost();
863 // Initialize a variable to track if this is an ad server.
864 boolean requestHostIsAdServer = false;
866 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
867 if (requestHost != null) {
868 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
869 if (adServersSet.contains(requestHost)) {
870 requestHostIsAdServer = true;
873 // Strip out the lowest subdomain of `requestHost`.
874 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
878 if (requestHostIsAdServer) { // It is an ad server.
879 // Return an empty `WebResourceResponse`.
880 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
881 } else { // It is not an ad server.
882 // `return null` loads the requested resource.
885 } else { // Ad blocking is disabled.
886 // `return null` loads the requested resource.
891 // Handle HTTP authentication requests.
893 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
894 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
895 httpAuthHandler = handler;
897 // Display the HTTP authentication dialog.
898 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
899 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
902 // Update the URL in urlTextBox when the page starts to load.
904 public void onPageStarted(WebView view, String url, Bitmap favicon) {
905 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
907 mainWebView.setVisibility(View.INVISIBLE);
910 // Hide the keyboard. `0` indicates no additional flags.
911 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
913 // Check to see if we are waiting on Orbot.
914 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
915 // 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.
916 formattedUrlString = url;
918 // Display the formatted URL text.
919 urlTextBox.setText(formattedUrlString);
921 // Apply text highlighting to `urlTextBox`.
924 // Apply any custom domain settings if the URL was loaded by navigating history.
925 if (navigatingHistory) {
926 applyDomainSettings(url);
929 // 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.
934 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
936 public void onPageFinished(WebView view, String url) {
937 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
938 urlIsLoading = false;
940 // Clear the cache and history if Incognito Mode is enabled.
941 if (incognitoModeEnabled) {
942 // Clear the cache. `true` includes disk files.
943 mainWebView.clearCache(true);
945 // Clear the back/forward history.
946 mainWebView.clearHistory();
948 // Manually delete cache folders.
950 // Delete the main `cache` folder.
951 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
953 // 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`.
954 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
955 } catch (IOException e) {
956 // Do nothing if an error is thrown.
960 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
961 if (!waitingForOrbot) {
962 // Check to see if `WebView` has set `url` to be `about:blank`.
963 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
964 // Set `formattedUrlString` to `""`.
965 formattedUrlString = "";
967 urlTextBox.setText(formattedUrlString);
969 // Request focus for `urlTextBox`.
970 urlTextBox.requestFocus();
972 // Display the keyboard.
973 inputMethodManager.showSoftInput(urlTextBox, 0);
975 // Apply the domain settings. This clears any settings from the previous domain.
976 applyDomainSettings(formattedUrlString);
977 } else { // `WebView` has loaded a webpage.
978 // Set `formattedUrlString`.
979 formattedUrlString = url;
981 // Only update `urlTextBox` if the user is not typing in it.
982 if (!urlTextBox.hasFocus()) {
983 // Display the formatted URL text.
984 urlTextBox.setText(formattedUrlString);
986 // Apply text highlighting to `urlTextBox`.
991 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
992 sslCertificate = mainWebView.getCertificate();
994 // 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.
995 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
996 // Initialize the current SSL certificate variables.
997 String currentWebsiteIssuedToCName = "";
998 String currentWebsiteIssuedToOName = "";
999 String currentWebsiteIssuedToUName = "";
1000 String currentWebsiteIssuedByCName = "";
1001 String currentWebsiteIssuedByOName = "";
1002 String currentWebsiteIssuedByUName = "";
1003 Date currentWebsiteSslStartDate = null;
1004 Date currentWebsiteSslEndDate = null;
1007 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1008 if (sslCertificate != null) {
1009 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1010 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1011 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1012 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1013 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1014 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1015 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1016 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1019 // 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`.
1020 String currentWebsiteSslStartDateString = "";
1021 String currentWebsiteSslEndDateString = "";
1022 String pinnedDomainSslStartDateString = "";
1023 String pinnedDomainSslEndDateString = "";
1025 // Convert the `Dates` to `Strings` if they are not `null`.
1026 if (currentWebsiteSslStartDate != null) {
1027 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1030 if (currentWebsiteSslEndDate != null) {
1031 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1034 if (pinnedDomainSslStartDate != null) {
1035 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1038 if (pinnedDomainSslEndDate != null) {
1039 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1042 // Check to see if the pinned SSL certificate matches the current website certificate.
1043 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) || !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) ||
1044 !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) || !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1045 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) { // The pinned SSL certificate doesn't match the current domain certificate.
1046 //Display the pinned SSL certificate mismatch `AlertDialog`.
1047 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1048 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1054 // Handle SSL Certificate errors.
1056 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1057 // Get the current website SSL certificate.
1058 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1060 // Extract the individual pieces of information from the current website SSL certificate.
1061 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1062 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1063 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1064 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1065 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1066 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1067 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1068 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1070 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1071 if (pinnedDomainSslCertificate &&
1072 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) && currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) &&
1073 currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) && currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1074 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) { // An SSL certificate is pinned and matches the current domain certificate.
1075 // Proceed to the website without displaying an error.
1077 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1078 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1079 sslErrorHandler = handler;
1081 // Display the SSL error `AlertDialog`.
1082 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1083 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1088 // Get a handle for the progress bar.
1089 final ProgressBar progressBar = findViewById(R.id.progress_bar);
1091 mainWebView.setWebChromeClient(new WebChromeClient() {
1092 // Update the progress bar when a page is loading.
1094 public void onProgressChanged(WebView view, int progress) {
1095 // Inject the night mode CSS if night mode is enabled.
1097 // `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.
1098 // `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.
1099 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
1100 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '" +
1101 "* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important; text-shadow: none !important; border: none !important;}" +
1102 "a {color: #1565C0 !important;}" +
1103 "'; parent.appendChild(style)})()", value -> {
1104 // Initialize a `Handler` to display `mainWebView`.
1105 Handler displayWebViewHandler = new Handler();
1107 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
1108 Runnable displayWebViewRunnable = () -> {
1109 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
1110 if (progressBar.getVisibility() == View.GONE) {
1111 mainWebView.setVisibility(View.VISIBLE);
1115 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
1116 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
1120 progressBar.setProgress(progress);
1121 if (progress < 100) {
1122 // Show the progress bar.
1123 progressBar.setVisibility(View.VISIBLE);
1125 // Hide the progress bar.
1126 progressBar.setVisibility(View.GONE);
1128 // Display `mainWebView` if night mode is disabled.
1129 // 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.
1131 mainWebView.setVisibility(View.VISIBLE);
1134 //Stop the `SwipeToRefresh` indicator if it is running
1135 swipeRefreshLayout.setRefreshing(false);
1139 // Set the favorite icon when it changes.
1141 public void onReceivedIcon(WebView view, Bitmap icon) {
1142 // Only update the favorite icon if the website has finished loading.
1143 if (progressBar.getVisibility() == View.GONE) {
1144 // Save a copy of the favorite icon.
1145 favoriteIconBitmap = icon;
1147 // Place the favorite icon in the appBar.
1148 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1152 // Save a copy of the title when it changes.
1154 public void onReceivedTitle(WebView view, String title) {
1155 // Save a copy of the title.
1156 webViewTitle = title;
1159 // Enter full screen video
1161 public void onShowCustomView(View view, CustomViewCallback callback) {
1162 // Pause the ad if this is the free flavor.
1163 if (BuildConfig.FLAVOR.contentEquals("free")) {
1164 BannerAd.pauseAd(adView);
1167 // Remove the translucent overlays.
1168 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1170 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1171 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1173 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1174 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1175 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1177 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1179 // Set `rootCoordinatorLayout` to fill the entire screen.
1180 rootCoordinatorLayout.setFitsSystemWindows(false);
1182 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1183 fullScreenVideoFrameLayout.addView(view);
1184 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1187 // Exit full screen video
1188 public void onHideCustomView() {
1189 // Hide `fullScreenVideoFrameLayout`.
1190 fullScreenVideoFrameLayout.removeAllViews();
1191 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1193 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1194 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1196 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1197 rootCoordinatorLayout.setFitsSystemWindows(true);
1199 // Show the ad if this is the free flavor.
1200 if (BuildConfig.FLAVOR.contentEquals("free")) {
1201 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1202 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1204 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1205 adView = findViewById(R.id.adview);
1210 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1211 registerForContextMenu(mainWebView);
1213 // Allow the downloading of files.
1214 mainWebView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {
1215 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1216 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1217 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1220 // Allow pinch to zoom.
1221 mainWebView.getSettings().setBuiltInZoomControls(true);
1223 // Hide zoom controls.
1224 mainWebView.getSettings().setDisplayZoomControls(false);
1226 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1227 mainWebView.getSettings().setUseWideViewPort(true);
1229 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1230 mainWebView.getSettings().setLoadWithOverviewMode(true);
1232 // Explicitly disable geolocation.
1233 mainWebView.getSettings().setGeolocationEnabled(false);
1235 // Initialize cookieManager.
1236 cookieManager = CookieManager.getInstance();
1238 // 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).
1239 customHeaders.put("X-Requested-With", "");
1241 // 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.
1242 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1244 // Get the intent that started the app.
1245 final Intent launchingIntent = getIntent();
1247 // Extract the launching intent data as `launchingIntentUriData`.
1248 final Uri launchingIntentUriData = launchingIntent.getData();
1250 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1251 if (launchingIntentUriData != null) {
1252 formattedUrlString = launchingIntentUriData.toString();
1255 // Get a handle for the `Runtime`.
1256 privacyBrowserRuntime = Runtime.getRuntime();
1258 // Store the application's private data directory.
1259 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`.
1261 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1262 inFullScreenBrowsingMode = false;
1264 // Initialize AdView for the free flavor.
1265 adView = findViewById(R.id.adview);
1267 // Initialize the privacy settings variables.
1268 javaScriptEnabled = false;
1269 firstPartyCookiesEnabled = false;
1270 thirdPartyCookiesEnabled = false;
1271 domStorageEnabled = false;
1272 saveFormDataEnabled = false;
1275 // Initialize `webViewTitle`.
1276 webViewTitle = getString(R.string.no_title);
1278 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1279 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1280 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1281 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1283 // If the favorite icon is null, load the default.
1284 if (favoriteIconBitmap == null) {
1285 favoriteIconBitmap = favoriteIconDefaultBitmap;
1288 // Apply the app settings from the shared preferences.
1291 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1292 if (!waitingForOrbot) {
1293 loadUrl(formattedUrlString);
1298 protected void onNewIntent(Intent intent) {
1299 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1302 if (intent.getData() != null) {
1303 // Get the intent data and convert it to a string.
1304 final Uri intentUriData = intent.getData();
1305 formattedUrlString = intentUriData.toString();
1308 // Close the navigation drawer if it is open.
1309 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1310 drawerLayout.closeDrawer(GravityCompat.START);
1313 // Load the website.
1314 loadUrl(formattedUrlString);
1316 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1317 mainWebView.requestFocus();
1321 public void onRestart() {
1324 // Apply the app settings, which may have been changed in `SettingsActivity`.
1327 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1328 updatePrivacyIcons(true);
1330 // Set the display webpage images mode.
1331 setDisplayWebpageImages();
1333 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1334 if (reloadOnRestart) {
1335 // Reload `mainWebView`.
1336 mainWebView.reload();
1338 // Reset `reloadOnRestartBoolean`.
1339 reloadOnRestart = false;
1342 // Load the URL on restart to apply changes to night mode.
1343 if (loadUrlOnRestart) {
1344 // Load the current `formattedUrlString`.
1345 loadUrl(formattedUrlString);
1347 // Reset `loadUrlOnRestart.
1348 loadUrlOnRestart = false;
1352 if (restartFromBookmarksActivity) {
1353 // Close the bookmarks drawer.
1354 drawerLayout.closeDrawer(GravityCompat.END);
1356 // Reload the bookmarks drawer.
1357 loadBookmarksFolder();
1359 // Reset `restartFromBookmarksActivity`.
1360 restartFromBookmarksActivity = false;
1364 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1366 public void onResume() {
1369 // Resume JavaScript (if enabled).
1370 mainWebView.resumeTimers();
1372 // Resume `mainWebView`.
1373 mainWebView.onResume();
1375 // Resume the adView for the free flavor.
1376 if (BuildConfig.FLAVOR.contentEquals("free")) {
1377 BannerAd.resumeAd(adView);
1382 public void onPause() {
1383 // Pause `mainWebView`.
1384 mainWebView.onPause();
1386 // Stop all JavaScript.
1387 mainWebView.pauseTimers();
1389 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1390 if (BuildConfig.FLAVOR.contentEquals("free")) {
1391 BannerAd.pauseAd(adView);
1398 public boolean onCreateOptionsMenu(Menu menu) {
1399 // Inflate the menu; this adds items to the action bar if it is present.
1400 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1402 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1405 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1406 updatePrivacyIcons(false);
1408 // Get handles for the menu items.
1409 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1410 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1411 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1412 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1414 // Only display third-party cookies if SDK >= 21
1415 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1417 // Get the shared preference values. `this` references the current context.
1418 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1420 // Set the status of the additional app bar icons. The default is `false`.
1421 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1422 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1423 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1424 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1425 } else { //Do not display the additional icons.
1426 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1427 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1428 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1435 public boolean onPrepareOptionsMenu(Menu menu) {
1436 // Get handles for the menu items.
1437 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1438 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1439 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1440 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1441 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1442 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1443 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1444 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1445 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1446 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1448 // Set the status of the menu item checkboxes.
1449 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1450 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1451 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1452 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1453 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1455 // Enable third-party cookies if first-party cookies are enabled.
1456 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1458 // Enable `DOM Storage` if JavaScript is enabled.
1459 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1461 // Enable `Clear Cookies` if there are any.
1462 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1464 // Get a count of the number of files in the `Local Storage` directory.
1465 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1466 int localStorageDirectoryNumberOfFiles = 0;
1467 if (localStorageDirectory.exists()) {
1468 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1471 // Get a count of the number of files in the `IndexedDB` directory.
1472 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1473 int indexedDBDirectoryNumberOfFiles = 0;
1474 if (indexedDBDirectory.exists()) {
1475 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1478 // Enable `Clear DOM Storage` if there is any.
1479 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1481 // Enable `Clear Form Data` is there is any.
1482 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1483 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1485 // Initialize font size variables.
1486 int fontSize = mainWebView.getSettings().getTextZoom();
1487 String fontSizeTitle;
1488 MenuItem selectedFontSizeMenuItem;
1490 // Prepare the font size title and current size menu item.
1493 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1494 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1498 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1499 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1503 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1504 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1508 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1509 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1513 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1514 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1518 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1519 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1523 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1524 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1528 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1529 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1533 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1534 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1538 // Set the font size title and select the current size menu item.
1539 fontSizeMenuItem.setTitle(fontSizeTitle);
1540 selectedFontSizeMenuItem.setChecked(true);
1542 // Only show `Refresh` if `swipeToRefresh` is disabled.
1543 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1545 // Run all the other default commands.
1546 super.onPrepareOptionsMenu(menu);
1548 // `return true` displays the menu.
1553 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1554 @SuppressLint("SetJavaScriptEnabled")
1555 // removeAllCookies is deprecated, but it is required for API < 21.
1556 @SuppressWarnings("deprecation")
1557 public boolean onOptionsItemSelected(MenuItem menuItem) {
1558 int menuItemId = menuItem.getItemId();
1560 // Set the commands that relate to the menu entries.
1561 switch (menuItemId) {
1562 case R.id.toggle_javascript:
1563 // Switch the status of javaScriptEnabled.
1564 javaScriptEnabled = !javaScriptEnabled;
1566 // Apply the new JavaScript status.
1567 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1569 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1570 updatePrivacyIcons(true);
1572 // Display a `Snackbar`.
1573 if (javaScriptEnabled) { // JavaScrip is enabled.
1574 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1575 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1576 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1577 } else { // Privacy mode.
1578 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1581 // Reload the WebView.
1582 mainWebView.reload();
1585 case R.id.toggle_first_party_cookies:
1586 // Switch the status of firstPartyCookiesEnabled.
1587 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1589 // Update the menu checkbox.
1590 menuItem.setChecked(firstPartyCookiesEnabled);
1592 // Apply the new cookie status.
1593 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1595 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1596 updatePrivacyIcons(true);
1598 // Display a `Snackbar`.
1599 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1600 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1601 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1602 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1603 } else { // Privacy mode.
1604 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1607 // Reload the WebView.
1608 mainWebView.reload();
1611 case R.id.toggle_third_party_cookies:
1612 if (Build.VERSION.SDK_INT >= 21) {
1613 // Switch the status of thirdPartyCookiesEnabled.
1614 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1616 // Update the menu checkbox.
1617 menuItem.setChecked(thirdPartyCookiesEnabled);
1619 // Apply the new cookie status.
1620 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1622 // Display a `Snackbar`.
1623 if (thirdPartyCookiesEnabled) {
1624 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1626 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1629 // Reload the WebView.
1630 mainWebView.reload();
1631 } // Else do nothing because SDK < 21.
1634 case R.id.toggle_dom_storage:
1635 // Switch the status of domStorageEnabled.
1636 domStorageEnabled = !domStorageEnabled;
1638 // Update the menu checkbox.
1639 menuItem.setChecked(domStorageEnabled);
1641 // Apply the new DOM Storage status.
1642 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1644 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1645 updatePrivacyIcons(true);
1647 // Display a `Snackbar`.
1648 if (domStorageEnabled) {
1649 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1651 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1654 // Reload the WebView.
1655 mainWebView.reload();
1658 case R.id.toggle_save_form_data:
1659 // Switch the status of saveFormDataEnabled.
1660 saveFormDataEnabled = !saveFormDataEnabled;
1662 // Update the menu checkbox.
1663 menuItem.setChecked(saveFormDataEnabled);
1665 // Apply the new form data status.
1666 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1668 // Display a `Snackbar`.
1669 if (saveFormDataEnabled) {
1670 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1672 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1675 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1676 updatePrivacyIcons(true);
1678 // Reload the WebView.
1679 mainWebView.reload();
1682 case R.id.clear_cookies:
1683 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1684 .setAction(R.string.undo, v -> {
1685 // Do nothing because everything will be handled by `onDismissed()` below.
1687 .addCallback(new Snackbar.Callback() {
1689 public void onDismissed(Snackbar snackbar, int event) {
1691 // The user pushed the `Undo` button.
1692 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1696 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1698 // `cookieManager.removeAllCookie()` varies by SDK.
1699 if (Build.VERSION.SDK_INT < 21) {
1700 cookieManager.removeAllCookie();
1702 // `null` indicates no callback.
1703 cookieManager.removeAllCookies(null);
1711 case R.id.clear_dom_storage:
1712 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1713 .setAction(R.string.undo, v -> {
1714 // Do nothing because everything will be handled by `onDismissed()` below.
1716 .addCallback(new Snackbar.Callback() {
1718 public void onDismissed(Snackbar snackbar, int event) {
1720 // The user pushed the `Undo` button.
1721 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1725 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1727 // Delete the DOM Storage.
1728 WebStorage webStorage = WebStorage.getInstance();
1729 webStorage.deleteAllData();
1731 // Manually remove `IndexedDB` if it exists.
1733 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1734 } catch (IOException e) {
1735 // Do nothing if an error is thrown.
1743 case R.id.clear_form_data:
1744 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1745 .setAction(R.string.undo, v -> {
1746 // Do nothing because everything will be handled by `onDismissed()` below.
1748 .addCallback(new Snackbar.Callback() {
1750 public void onDismissed(Snackbar snackbar, int event) {
1752 // The user pushed the `Undo` button.
1753 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1757 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1759 // Delete the form data.
1760 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1761 mainWebViewDatabase.clearFormData();
1768 case R.id.font_size_twenty_five_percent:
1769 mainWebView.getSettings().setTextZoom(25);
1772 case R.id.font_size_fifty_percent:
1773 mainWebView.getSettings().setTextZoom(50);
1776 case R.id.font_size_seventy_five_percent:
1777 mainWebView.getSettings().setTextZoom(75);
1780 case R.id.font_size_one_hundred_percent:
1781 mainWebView.getSettings().setTextZoom(100);
1784 case R.id.font_size_one_hundred_twenty_five_percent:
1785 mainWebView.getSettings().setTextZoom(125);
1788 case R.id.font_size_one_hundred_fifty_percent:
1789 mainWebView.getSettings().setTextZoom(150);
1792 case R.id.font_size_one_hundred_seventy_five_percent:
1793 mainWebView.getSettings().setTextZoom(175);
1796 case R.id.font_size_two_hundred_percent:
1797 mainWebView.getSettings().setTextZoom(200);
1800 case R.id.display_images:
1801 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1802 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1803 mainWebView.reload();
1804 } else { // Images are not currently loaded automatically.
1805 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1808 // Set `onTheFlyDisplayImagesSet`.
1809 onTheFlyDisplayImagesSet = true;
1813 // Setup the share string.
1814 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1816 // Create the share intent.
1817 Intent shareIntent = new Intent();
1818 shareIntent.setAction(Intent.ACTION_SEND);
1819 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1820 shareIntent.setType("text/plain");
1823 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1826 case R.id.find_on_page:
1827 // Hide the URL app bar.
1828 supportAppBar.setVisibility(View.GONE);
1830 // Show the Find on Page `RelativeLayout`.
1831 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1833 // 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
1834 findOnPageEditText.postDelayed(() -> {
1835 // Set the focus on `findOnPageEditText`.
1836 findOnPageEditText.requestFocus();
1838 // Display the keyboard. `0` sets no input flags.
1839 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1844 // Get a `PrintManager` instance.
1845 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1847 // Convert `mainWebView` to `printDocumentAdapter`.
1848 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1850 // Remove the lint error below that `printManager` might be `null`.
1851 assert printManager != null;
1853 // Print the document. The print attributes are `null`.
1854 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1857 case R.id.add_to_homescreen:
1858 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1859 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1860 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1862 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1866 mainWebView.reload();
1870 // Don't consume the event.
1871 return super.onOptionsItemSelected(menuItem);
1875 // removeAllCookies is deprecated, but it is required for API < 21.
1876 @SuppressWarnings("deprecation")
1878 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1879 int menuItemId = menuItem.getItemId();
1881 switch (menuItemId) {
1887 if (mainWebView.canGoBack()) {
1888 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1889 navigatingHistory = true;
1891 // Load the previous website in the history.
1892 mainWebView.goBack();
1897 if (mainWebView.canGoForward()) {
1898 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1899 navigatingHistory = true;
1901 // Load the next website in the history.
1902 mainWebView.goForward();
1907 // Get the `WebBackForwardList`.
1908 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1910 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1911 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1912 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1915 case R.id.downloads:
1916 // Launch the system Download Manager.
1917 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1919 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1920 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1922 startActivity(downloadManagerIntent);
1926 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1927 currentDomainName = "";
1929 // Launch `DomainsActivity`.
1930 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1931 startActivity(domainsIntent);
1935 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1936 currentDomainName = "";
1938 // Launch `SettingsActivity`.
1939 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1940 startActivity(settingsIntent);
1944 // Launch `GuideActivity`.
1945 Intent guideIntent = new Intent(this, GuideActivity.class);
1946 startActivity(guideIntent);
1950 // Launch `AboutActivity`.
1951 Intent aboutIntent = new Intent(this, AboutActivity.class);
1952 startActivity(aboutIntent);
1955 case R.id.clearAndExit:
1956 // Get a handle for `sharedPreferences`. `this` references the current context.
1957 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1959 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1962 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1963 // The command to remove cookies changed slightly in API 21.
1964 if (Build.VERSION.SDK_INT >= 21) {
1965 cookieManager.removeAllCookies(null);
1967 cookieManager.removeAllCookie();
1970 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1972 // We have to use two commands because `Runtime.exec()` does not like `*`.
1973 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1974 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1975 } catch (IOException e) {
1976 // Do nothing if an error is thrown.
1980 // Clear DOM storage.
1981 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1982 // Ask `WebStorage` to clear the DOM storage.
1983 WebStorage webStorage = WebStorage.getInstance();
1984 webStorage.deleteAllData();
1986 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1988 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1989 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1991 // We have to use multiple commands because `Runtime.exec()` does not like `*`.
1992 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1993 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1994 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1995 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1996 } catch (IOException e) {
1997 // Do nothing if an error is thrown.
2002 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2003 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2004 webViewDatabase.clearFormData();
2006 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2008 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2009 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2010 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2011 } catch (IOException e) {
2012 // Do nothing if an error is thrown.
2017 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2018 // `true` includes disk files.
2019 mainWebView.clearCache(true);
2021 // Manually delete the cache directories.
2023 // Delete the main cache directory.
2024 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2026 // 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.
2027 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2028 } catch (IOException e) {
2029 // Do nothing if an error is thrown.
2033 // Clear SSL certificate preferences.
2034 mainWebView.clearSslPreferences();
2036 // Clear the back/forward history.
2037 mainWebView.clearHistory();
2039 // Clear `formattedUrlString`.
2040 formattedUrlString = null;
2042 // Clear `customHeaders`.
2043 customHeaders.clear();
2045 // Detach all views from `mainWebViewRelativeLayout`.
2046 mainWebViewRelativeLayout.removeAllViews();
2048 // Destroy the internal state of `mainWebView`.
2049 mainWebView.destroy();
2051 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2052 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2053 if (clearEverything) {
2055 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2056 } catch (IOException e) {
2057 // Do nothing if an error is thrown.
2061 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2062 if (Build.VERSION.SDK_INT >= 21) {
2063 finishAndRemoveTask();
2068 // Remove the terminated program from RAM. The status code is `0`.
2073 // Close the navigation drawer.
2074 drawerLayout.closeDrawer(GravityCompat.START);
2079 public void onPostCreate(Bundle savedInstanceState) {
2080 super.onPostCreate(savedInstanceState);
2082 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2083 drawerToggle.syncState();
2087 public void onConfigurationChanged(Configuration newConfig) {
2088 super.onConfigurationChanged(newConfig);
2090 // Reload the ad for the free flavor if we are not in full screen mode.
2091 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2093 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2095 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2096 adView = findViewById(R.id.adview);
2099 // `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
2100 // ActivityCompat.invalidateOptionsMenu(this);
2104 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2105 // Store the `HitTestResult`.
2106 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2109 final String imageUrl;
2110 final String linkUrl;
2112 // Get a handle for the `ClipboardManager`.
2113 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2115 // Remove the lint errors below that `clipboardManager` might be `null`.
2116 assert clipboardManager != null;
2118 switch (hitTestResult.getType()) {
2119 // `SRC_ANCHOR_TYPE` is a link.
2120 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2121 // Get the target URL.
2122 linkUrl = hitTestResult.getExtra();
2124 // Set the target URL as the title of the `ContextMenu`.
2125 menu.setHeaderTitle(linkUrl);
2127 // Add a `Load URL` entry.
2128 menu.add(R.string.load_url).setOnMenuItemClickListener(item -> {
2133 // Add a `Copy URL` entry.
2134 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2135 // Save the link URL in a `ClipData`.
2136 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2138 // Set the `ClipData` as the clipboard's primary clip.
2139 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2143 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2144 menu.add(R.string.cancel);
2147 case WebView.HitTestResult.EMAIL_TYPE:
2148 // Get the target URL.
2149 linkUrl = hitTestResult.getExtra();
2151 // Set the target URL as the title of the `ContextMenu`.
2152 menu.setHeaderTitle(linkUrl);
2154 // Add a `Write Email` entry.
2155 menu.add(R.string.write_email).setOnMenuItemClickListener(item -> {
2156 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2157 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2159 // Parse the url and set it as the data for the `Intent`.
2160 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2162 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2163 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2166 startActivity(emailIntent);
2170 // Add a `Copy Email Address` entry.
2171 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(item -> {
2172 // Save the email address in a `ClipData`.
2173 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2175 // Set the `ClipData` as the clipboard's primary clip.
2176 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2180 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2181 menu.add(R.string.cancel);
2184 // `IMAGE_TYPE` is an image.
2185 case WebView.HitTestResult.IMAGE_TYPE:
2186 // Get the image URL.
2187 imageUrl = hitTestResult.getExtra();
2189 // Set the image URL as the title of the `ContextMenu`.
2190 menu.setHeaderTitle(imageUrl);
2192 // Add a `View Image` entry.
2193 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2198 // Add a `Download Image` entry.
2199 menu.add(R.string.download_image).setOnMenuItemClickListener(item -> {
2200 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2201 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2202 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2206 // Add a `Copy URL` entry.
2207 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2208 // Save the image URL in a `ClipData`.
2209 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2211 // Set the `ClipData` as the clipboard's primary clip.
2212 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2216 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2217 menu.add(R.string.cancel);
2221 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2222 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2223 // Get the image URL.
2224 imageUrl = hitTestResult.getExtra();
2226 // Set the image URL as the title of the `ContextMenu`.
2227 menu.setHeaderTitle(imageUrl);
2229 // Add a `View Image` entry.
2230 menu.add(R.string.view_image).setOnMenuItemClickListener(item -> {
2235 // Add a `Download Image` entry.
2236 menu.add(R.string.download_image).setOnMenuItemClickListener(item -> {
2237 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2238 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2239 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2243 // Add a `Copy URL` entry.
2244 menu.add(R.string.copy_url).setOnMenuItemClickListener(item -> {
2245 // Save the image URL in a `ClipData`.
2246 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2248 // Set the `ClipData` as the clipboard's primary clip.
2249 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2253 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2254 menu.add(R.string.cancel);
2260 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2261 // Get the `EditTexts` from the `dialogFragment`.
2262 EditText createBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2263 EditText createBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2265 // Extract the strings from the `EditTexts`.
2266 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2267 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2269 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2270 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2271 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2272 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2274 // Display the new bookmark below the current items in the (0 indexed) list.
2275 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2277 // Create the bookmark.
2278 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, currentBookmarksFolder, newBookmarkDisplayOrder, favoriteIconByteArray);
2280 // Update `bookmarksCursor` with the current contents of this folder.
2281 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2283 // Update the `ListView`.
2284 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2286 // Scroll to the new bookmark.
2287 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2291 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2292 // Get handles for the views in `dialogFragment`.
2293 EditText createFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2294 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2295 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2297 // Get new folder name string.
2298 String folderNameString = createFolderNameEditText.getText().toString();
2300 // Get the new folder icon `Bitmap`.
2301 Bitmap folderIconBitmap;
2302 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2303 // Get the default folder icon and convert it to a `Bitmap`.
2304 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2305 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2306 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2307 } else { // Use the `WebView` favorite icon.
2308 folderIconBitmap = favoriteIconBitmap;
2311 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2312 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2313 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2314 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2316 // Move all the bookmarks down one in the display order.
2317 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2318 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2319 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2322 // Create the folder, which will be placed at the top of the `ListView`.
2323 bookmarksDatabaseHelper.createFolder(folderNameString, currentBookmarksFolder, folderIconByteArray);
2325 // Update `bookmarksCursor` with the current contents of this folder.
2326 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2328 // Update the `ListView`.
2329 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2331 // Scroll to the new folder.
2332 bookmarksListView.setSelection(0);
2336 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2337 // Get shortcutNameEditText from the alert dialog.
2338 EditText shortcutNameEditText = dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2340 // Create the bookmark shortcut based on formattedUrlString.
2341 Intent bookmarkShortcut = new Intent();
2342 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
2343 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
2345 // Place the bookmark shortcut on the home screen.
2346 Intent placeBookmarkShortcut = new Intent();
2347 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
2348 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
2349 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
2350 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
2351 sendBroadcast(placeBookmarkShortcut);
2355 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2356 // Download the image if it has an HTTP or HTTPS URI.
2357 if (imageUrl.startsWith("http")) {
2358 // Get a handle for the system `DOWNLOAD_SERVICE`.
2359 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2361 // Parse `imageUrl`.
2362 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2364 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2365 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2366 if (firstPartyCookiesEnabled) {
2367 // Get the cookies for `imageUrl`.
2368 String cookies = cookieManager.getCookie(imageUrl);
2370 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2371 downloadRequest.addRequestHeader("Cookie", cookies);
2374 // Get the file name from `dialogFragment`.
2375 EditText downloadImageNameEditText = dialogFragment.getDialog().findViewById(R.id.download_image_name);
2376 String imageName = downloadImageNameEditText.getText().toString();
2378 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2379 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2380 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2381 } else { // Only set the title using `imageName`.
2382 downloadRequest.setTitle(imageName);
2385 // Allow `MediaScanner` to index the download if it is a media file.
2386 downloadRequest.allowScanningByMediaScanner();
2388 // Add the URL as the description for the download.
2389 downloadRequest.setDescription(imageUrl);
2391 // Show the download notification after the download is completed.
2392 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2394 // Remove the lint warning below that `downloadManager` might be `null`.
2395 assert downloadManager != null;
2397 // Initiate the download.
2398 downloadManager.enqueue(downloadRequest);
2399 } else { // The image is not an HTTP or HTTPS URI.
2400 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2405 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2406 // Download the file if it has an HTTP or HTTPS URI.
2407 if (downloadUrl.startsWith("http")) {
2409 // Get a handle for the system `DOWNLOAD_SERVICE`.
2410 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2412 // Parse `downloadUrl`.
2413 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2415 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2416 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2417 if (firstPartyCookiesEnabled) {
2418 // Get the cookies for `downloadUrl`.
2419 String cookies = cookieManager.getCookie(downloadUrl);
2421 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2422 downloadRequest.addRequestHeader("Cookie", cookies);
2425 // Get the file name from `dialogFragment`.
2426 EditText downloadFileNameEditText = dialogFragment.getDialog().findViewById(R.id.download_file_name);
2427 String fileName = downloadFileNameEditText.getText().toString();
2429 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2430 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2431 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2432 } else { // Only set the title using `fileName`.
2433 downloadRequest.setTitle(fileName);
2436 // Allow `MediaScanner` to index the download if it is a media file.
2437 downloadRequest.allowScanningByMediaScanner();
2439 // Add the URL as the description for the download.
2440 downloadRequest.setDescription(downloadUrl);
2442 // Show the download notification after the download is completed.
2443 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2445 // Remove the lint warning below that `downloadManager` might be `null`.
2446 assert downloadManager != null;
2448 // Initiate the download.
2449 downloadManager.enqueue(downloadRequest);
2450 } else { // The download is not an HTTP or HTTPS URI.
2451 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2456 public void onSaveBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2457 // Get handles for the views from `dialogFragment`.
2458 EditText editBookmarkNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2459 EditText editBookmarkUrlEditText = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2460 RadioButton currentBookmarkIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2462 // Store the bookmark strings.
2463 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2464 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2466 // Update the bookmark.
2467 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2468 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2469 } else { // Update the bookmark using the `WebView` favorite icon.
2470 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2471 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2472 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2473 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2475 // Update the bookmark and the favorite icon.
2476 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2479 // Update `bookmarksCursor` with the current contents of this folder.
2480 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2482 // Update the `ListView`.
2483 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2487 public void onSaveBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2488 // Get handles for the views from `dialogFragment`.
2489 EditText editFolderNameEditText = dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2490 RadioButton currentFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2491 RadioButton defaultFolderIconRadioButton = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2492 ImageView folderIconImageView = dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_imageview);
2494 // Get the new folder name.
2495 String newFolderNameString = editFolderNameEditText.getText().toString();
2497 // Check if the favorite icon has changed.
2498 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2499 // Update the name in the database.
2500 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2501 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2502 // Get the new folder icon `Bitmap`.
2503 Bitmap folderIconBitmap;
2504 if (defaultFolderIconRadioButton.isChecked()) {
2505 // Get the default folder icon and convert it to a `Bitmap`.
2506 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2507 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2508 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2509 } else { // Use the `WebView` favorite icon.
2510 folderIconBitmap = favoriteIconBitmap;
2513 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2514 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2515 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2516 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2518 // Update the folder icon in the database.
2519 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2520 } else { // The folder icon and the name have changed.
2521 // Get the new folder icon `Bitmap`.
2522 Bitmap folderIconBitmap;
2523 if (defaultFolderIconRadioButton.isChecked()) {
2524 // Get the default folder icon and convert it to a `Bitmap`.
2525 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2526 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2527 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2528 } else { // Use the `WebView` favorite icon.
2529 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2532 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2533 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2534 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2535 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2537 // Update the folder name and icon in the database.
2538 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2541 // Update `bookmarksCursor` with the current contents of this folder.
2542 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2544 // Update the `ListView`.
2545 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2549 public void onHttpAuthenticationCancel() {
2550 // Cancel the `HttpAuthHandler`.
2551 httpAuthHandler.cancel();
2555 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2556 // Get handles for the `EditTexts`.
2557 EditText usernameEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2558 EditText passwordEditText = dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2560 // Proceed with the HTTP authentication.
2561 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2564 public void viewSslCertificate(View view) {
2565 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2566 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2567 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2571 public void onSslErrorCancel() {
2572 sslErrorHandler.cancel();
2576 public void onSslErrorProceed() {
2577 sslErrorHandler.proceed();
2581 public void onSslMismatchBack() {
2582 if (mainWebView.canGoBack()) { // There is a back page in the history.
2583 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2584 navigatingHistory = true;
2587 mainWebView.goBack();
2588 } else { // There are no pages to go back to.
2589 // Load a blank page
2595 public void onSslMismatchProceed() {
2596 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2597 ignorePinnedSslCertificate = true;
2601 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2602 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2603 navigatingHistory = true;
2605 // Load the history entry.
2606 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2610 public void onClearHistory() {
2611 // Clear the history.
2612 mainWebView.clearHistory();
2615 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2617 public void onBackPressed() {
2618 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2619 // Close the navigation drawer.
2620 drawerLayout.closeDrawer(GravityCompat.START);
2621 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2622 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2623 // close the bookmarks drawer.
2624 drawerLayout.closeDrawer(GravityCompat.END);
2625 } else { // A subfolder is displayed.
2626 // Place the former parent folder in `currentFolder`.
2627 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2629 // Load the new folder.
2630 loadBookmarksFolder();
2633 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2634 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2635 navigatingHistory = true;
2638 mainWebView.goBack();
2639 } else { // There isn't anything to do in Privacy Browser.
2640 // Pass `onBackPressed()` to the system.
2641 super.onBackPressed();
2645 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2646 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2647 String unformattedUrlString = urlTextBox.getText().toString().trim();
2649 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2650 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2651 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2652 if (!unformattedUrlString.startsWith("http")) {
2653 unformattedUrlString = "http://" + unformattedUrlString;
2656 // Initialize `unformattedUrl`.
2657 URL unformattedUrl = null;
2659 // 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.
2661 unformattedUrl = new URL(unformattedUrlString);
2662 } catch (MalformedURLException e) {
2663 e.printStackTrace();
2666 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2667 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2668 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2669 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2670 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2671 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2674 Uri.Builder formattedUri = new Uri.Builder();
2675 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2677 // Decode `formattedUri` as a `String` in `UTF-8`.
2678 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2680 // Sanitize the search input and convert it to a search.
2681 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2683 // Add the base search URL.
2684 formattedUrlString = searchURL + encodedUrlString;
2687 loadUrl(formattedUrlString);
2691 private void loadUrl(String url) {
2692 // Apply any custom domain settings.
2693 applyDomainSettings(url);
2696 mainWebView.loadUrl(url, customHeaders);
2698 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2699 urlIsLoading = true;
2702 public void findPreviousOnPage(View view) {
2703 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2704 mainWebView.findNext(false);
2707 public void findNextOnPage(View view) {
2708 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2709 mainWebView.findNext(true);
2712 public void closeFindOnPage(View view) {
2713 // Delete the contents of `find_on_page_edittext`.
2714 findOnPageEditText.setText(null);
2716 // Clear the highlighted phrases.
2717 mainWebView.clearMatches();
2719 // Hide the Find on Page `RelativeLayout`.
2720 findOnPageLinearLayout.setVisibility(View.GONE);
2722 // Show the URL app bar.
2723 supportAppBar.setVisibility(View.VISIBLE);
2725 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2726 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2729 private void applyAppSettings() {
2730 // Get a handle for `sharedPreferences`. `this` references the current context.
2731 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2733 // Store the values from `sharedPreferences` in variables.
2734 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2735 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2736 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2737 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2738 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2739 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2740 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2741 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2742 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2743 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2744 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2745 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2746 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2747 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2748 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2750 // Set the homepage, search, and proxy options.
2751 if (proxyThroughOrbot) { // Set the Tor options.
2752 // Set `torHomepageString` as `homepage`.
2753 homepage = torHomepageString;
2755 // If formattedUrlString is null assign the homepage to it.
2756 if (formattedUrlString == null) {
2757 formattedUrlString = homepage;
2760 // Set the search URL.
2761 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2762 searchURL = torSearchCustomURLString;
2763 } else { // Use the string from the pre-built list.
2764 searchURL = torSearchString;
2767 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2768 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2770 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2772 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2774 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2777 // Display a message to the user if we are waiting on Orbot.
2778 if (!orbotStatus.equals("ON")) {
2779 // Set `waitingForOrbot`.
2780 waitingForOrbot = true;
2782 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2783 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2785 } else { // Set the non-Tor options.
2786 // Set `homepageString` as `homepage`.
2787 homepage = homepageString;
2789 // If formattedUrlString is null assign the homepage to it.
2790 if (formattedUrlString == null) {
2791 formattedUrlString = homepage;
2794 // Set the search URL.
2795 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2796 searchURL = searchCustomURLString;
2797 } else { // Use the string from the pre-built list.
2798 searchURL = searchString;
2801 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2802 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2804 // Set the default `appBar` background. `this` refers to the context.
2806 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2808 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2811 // Reset `waitingForOrbot.
2812 waitingForOrbot = false;
2815 // Set swipe to refresh.
2816 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2818 // Set Do Not Track status.
2819 if (doNotTrackEnabled) {
2820 customHeaders.put("DNT", "1");
2822 customHeaders.remove("DNT");
2825 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2826 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2827 if (hideSystemBarsOnFullscreen) { // Hide everything.
2828 // Remove the translucent navigation setting if it is currently flagged.
2829 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2831 // Remove the translucent status bar overlay.
2832 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2834 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2835 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2837 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2838 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2839 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2841 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2842 } else { // Hide everything except the status and navigation bars.
2843 // Add the translucent status flag if it is unset.
2844 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2846 if (translucentNavigationBarOnFullscreen) {
2847 // Set the navigation bar to be translucent.
2848 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2850 // Set the navigation bar to be black.
2851 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2854 } else { // Switch to normal viewing mode.
2855 // Reset `inFullScreenBrowsingMode` to `false`.
2856 inFullScreenBrowsingMode = false;
2858 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2859 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2863 // Show the `BannerAd` in the free flavor.
2864 if (BuildConfig.FLAVOR.contentEquals("free")) {
2865 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2866 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2868 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2869 adView = findViewById(R.id.adview);
2872 // Remove the translucent navigation bar flag if it is set.
2873 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2875 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2876 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2878 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2879 rootCoordinatorLayout.setSystemUiVisibility(0);
2881 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2882 rootCoordinatorLayout.setFitsSystemWindows(true);
2886 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2887 @SuppressWarnings("deprecation")
2888 private void applyDomainSettings(String url) {
2889 // Reset `navigatingHistory`.
2890 navigatingHistory = false;
2892 // Parse the URL into a URI.
2893 Uri uri = Uri.parse(url);
2895 // Extract the domain from `uri`.
2896 String hostName = uri.getHost();
2898 // Initialize `loadingNewDomainName`.
2899 boolean loadingNewDomainName;
2901 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2902 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2903 //noinspection SimplifiableIfStatement
2904 if ((hostName == null) || (currentDomainName == null)) {
2905 loadingNewDomainName = true;
2906 } else { // Determine if `hostName` equals `currentDomainName`.
2907 loadingNewDomainName = !hostName.equals(currentDomainName);
2910 // 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.
2911 if (loadingNewDomainName) {
2912 // Set the new `hostname` as the `currentDomainName`.
2913 currentDomainName = hostName;
2915 // Reset `ignorePinnedSslCertificate`.
2916 ignorePinnedSslCertificate = false;
2918 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2919 favoriteIconBitmap = favoriteIconDefaultBitmap;
2920 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2922 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2923 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2924 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2926 // Get a full cursor from `domainsDatabaseHelper`.
2927 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2929 // Initialize `domainSettingsSet`.
2930 Set<String> domainSettingsSet = new HashSet<>();
2932 // Get the domain name column index.
2933 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2935 // Populate `domainSettingsSet`.
2936 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2937 // Move `domainsCursor` to the current row.
2938 domainNameCursor.moveToPosition(i);
2940 // Store the domain name in `domainSettingsSet`.
2941 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2944 // Close `domainNameCursor.
2945 domainNameCursor.close();
2947 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2948 domainSettingsApplied = false;
2949 String domainNameInDatabase = null;
2951 // Check the hostname.
2952 if (domainSettingsSet.contains(hostName)) {
2953 domainSettingsApplied = true;
2954 domainNameInDatabase = hostName;
2957 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2958 if (hostName != null) {
2959 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2960 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2961 domainSettingsApplied = true;
2962 domainNameInDatabase = "*." + hostName;
2965 // Strip out the lowest subdomain of `host`.
2966 hostName = hostName.substring(hostName.indexOf(".") + 1);
2970 // Get a handle for the shared preference. `this` references the current context.
2971 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2973 // Store the general preference information.
2974 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2975 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2976 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2977 nightMode = sharedPreferences.getBoolean("night_mode", false);
2979 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2980 // Get a cursor for the current host and move it to the first position.
2981 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2982 currentHostDomainSettingsCursor.moveToFirst();
2984 // Get the settings from the cursor.
2985 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
2986 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2987 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2988 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2989 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2990 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2991 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2992 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2993 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2994 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
2995 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
2996 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
2997 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
2998 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
2999 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3000 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3001 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3003 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3004 switch (nightModeInt) {
3005 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3009 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3014 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3016 javaScriptEnabled = true;
3019 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3020 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3021 pinnedDomainSslStartDate = null;
3023 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3026 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3027 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3028 pinnedDomainSslEndDate = null;
3030 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3033 // Close `currentHostDomainSettingsCursor`.
3034 currentHostDomainSettingsCursor.close();
3036 // Apply the domain settings.
3037 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3038 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3039 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3040 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3042 // Apply the font size.
3043 if (fontSize == 0) { // Apply the default font size.
3044 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3045 } else { // Apply the specified font size.
3046 mainWebView.getSettings().setTextZoom(fontSize);
3049 // Set third-party cookies status if API >= 21.
3050 if (Build.VERSION.SDK_INT >= 21) {
3051 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3054 // 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>
3055 if (!urlIsLoading) {
3056 switch (userAgentString) {
3057 case "System default user agent":
3058 // Set the user agent according to the system default.
3059 switch (defaultUserAgentString) {
3060 case "WebView default user agent":
3061 // Set the user agent to `""`, which uses the default value.
3062 mainWebView.getSettings().setUserAgentString("");
3065 case "Custom user agent":
3066 // Set the custom user agent.
3067 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3071 // Use the selected user agent.
3072 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3076 case "WebView default user agent":
3077 // Set the user agent to `""`, which uses the default value.
3078 mainWebView.getSettings().setUserAgentString("");
3082 // Use the selected user agent.
3083 mainWebView.getSettings().setUserAgentString(userAgentString);
3087 // 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.
3089 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3091 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3093 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3094 // Store the values from `sharedPreferences` in variables.
3095 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3096 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3097 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3098 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3099 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3101 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3103 javaScriptEnabled = true;
3106 // Apply the default settings.
3107 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3108 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3109 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3110 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3111 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3113 // Reset the pinned SSL certificate information.
3114 domainSettingsDatabaseId = -1;
3115 pinnedDomainSslCertificate = false;
3116 pinnedDomainSslIssuedToCNameString = "";
3117 pinnedDomainSslIssuedToONameString = "";
3118 pinnedDomainSslIssuedToUNameString = "";
3119 pinnedDomainSslIssuedByCNameString = "";
3120 pinnedDomainSslIssuedByONameString = "";
3121 pinnedDomainSslIssuedByUNameString = "";
3122 pinnedDomainSslStartDate = null;
3123 pinnedDomainSslEndDate = null;
3125 // Set third-party cookies status if API >= 21.
3126 if (Build.VERSION.SDK_INT >= 21) {
3127 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3130 // 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>
3131 if (!urlIsLoading) {
3132 switch (defaultUserAgentString) {
3133 case "WebView default user agent":
3134 // Set the user agent to `""`, which uses the default value.
3135 mainWebView.getSettings().setUserAgentString("");
3138 case "Custom user agent":
3139 // Set the custom user agent.
3140 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3144 // Use the selected user agent.
3145 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3149 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3150 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3153 // Close `domainsDatabaseHelper`.
3154 domainsDatabaseHelper.close();
3156 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3157 onTheFlyDisplayImagesSet = false;
3158 setDisplayWebpageImages();
3160 // Update the privacy icons, but only if `mainMenu` has already been populated.
3161 if (mainMenu != null) {
3162 updatePrivacyIcons(true);
3167 private void setDisplayWebpageImages() {
3168 if (!onTheFlyDisplayImagesSet) {
3169 if (domainSettingsApplied) { // Custom domain settings are applied.
3170 switch (displayWebpageImagesInt) {
3171 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3172 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3175 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3176 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3179 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3180 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3183 } else { // Default settings are applied.
3184 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3189 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3190 // Get handles for the icons.
3191 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3192 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3193 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3194 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3196 // Update `privacyIcon`.
3197 if (javaScriptEnabled) { // JavaScript is enabled.
3198 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3199 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3200 privacyIconMenuItem.setIcon(R.drawable.warning);
3201 } else { // All the dangerous features are disabled.
3202 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3205 // Update `firstPartyCookiesIcon`.
3206 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3207 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3208 } else { // First-party cookies are disabled.
3210 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3212 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3216 // Update `domStorageIcon`.
3217 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3218 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3219 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3221 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3223 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3225 } else { // JavaScript is disabled, so DOM storage is ghosted.
3227 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3229 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3233 // Update `formDataIcon`.
3234 if (saveFormDataEnabled) { // Form data is enabled.
3235 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3236 } else { // Form data is disabled.
3238 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3240 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3244 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
3245 if (runInvalidateOptionsMenu) {
3246 ActivityCompat.invalidateOptionsMenu(this);
3250 private void highlightUrlText() {
3251 String urlString = urlTextBox.getText().toString();
3253 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
3254 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3255 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
3256 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3259 // Get the index of the `/` immediately after the domain name.
3260 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3262 // De-emphasize the text after the domain name.
3263 if (endOfDomainName > 0) {
3264 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3268 private void loadBookmarksFolder() {
3269 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3270 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3272 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3273 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3275 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3276 // Inflate the individual item layout. `false` does not attach it to the root.
3277 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3281 public void bindView(View view, Context context, Cursor cursor) {
3282 // Get handles for the views.
3283 ImageView bookmarkFavoriteIcon = view.findViewById(R.id.bookmark_favorite_icon);
3284 TextView bookmarkNameTextView = view.findViewById(R.id.bookmark_name);
3286 // Get the favorite icon byte array from the `Cursor`.
3287 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3289 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3290 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3292 // Display the bitmap in `bookmarkFavoriteIcon`.
3293 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3295 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3296 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3297 bookmarkNameTextView.setText(bookmarkNameString);
3299 // Make the font bold for folders.
3300 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3301 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3302 } else { // Reset the font to default for normal bookmarks.
3303 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3308 // Populate the `ListView` with the adapter.
3309 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3311 // Set the bookmarks drawer title.
3312 if (currentBookmarksFolder.isEmpty()) {
3313 bookmarksTitleTextView.setText(R.string.bookmarks);
3315 bookmarksTitleTextView.setText(currentBookmarksFolder);