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.DownloadListener;
82 import android.webkit.HttpAuthHandler;
83 import android.webkit.SslErrorHandler;
84 import android.webkit.ValueCallback;
85 import android.webkit.WebBackForwardList;
86 import android.webkit.WebChromeClient;
87 import android.webkit.WebResourceResponse;
88 import android.webkit.WebStorage;
89 import android.webkit.WebView;
90 import android.webkit.WebViewClient;
91 import android.webkit.WebViewDatabase;
92 import android.widget.AdapterView;
93 import android.widget.CursorAdapter;
94 import android.widget.EditText;
95 import android.widget.FrameLayout;
96 import android.widget.ImageView;
97 import android.widget.LinearLayout;
98 import android.widget.ListView;
99 import android.widget.ProgressBar;
100 import android.widget.RadioButton;
101 import android.widget.RelativeLayout;
102 import android.widget.TextView;
104 import com.stoutner.privacybrowser.BannerAd;
105 import com.stoutner.privacybrowser.BuildConfig;
106 import com.stoutner.privacybrowser.R;
107 import com.stoutner.privacybrowser.dialogs.CreateBookmarkDialog;
108 import com.stoutner.privacybrowser.dialogs.CreateBookmarkFolderDialog;
109 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
110 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
111 import com.stoutner.privacybrowser.dialogs.EditBookmarkDialog;
112 import com.stoutner.privacybrowser.dialogs.EditBookmarkFolderDialog;
113 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
114 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
115 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
116 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
117 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
118 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
119 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
120 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
121 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
123 import java.io.BufferedReader;
124 import java.io.ByteArrayInputStream;
125 import java.io.ByteArrayOutputStream;
127 import java.io.IOException;
128 import java.io.InputStreamReader;
129 import java.io.UnsupportedEncodingException;
130 import java.net.MalformedURLException;
132 import java.net.URLDecoder;
133 import java.net.URLEncoder;
134 import java.util.Date;
135 import java.util.HashMap;
136 import java.util.HashSet;
137 import java.util.Map;
138 import java.util.Set;
140 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
141 public class MainWebViewActivity extends AppCompatActivity implements CreateBookmarkDialog.CreateBookmarkListener, CreateBookmarkFolderDialog.CreateBookmarkFolderListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
142 DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, EditBookmarkDialog.EditBookmarkListener, EditBookmarkFolderDialog.EditBookmarkFolderListener, HttpAuthenticationDialog.HttpAuthenticationListener,
143 NavigationView.OnNavigationItemSelectedListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, UrlHistoryDialog.UrlHistoryListener {
145 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`,
146 // `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`,
147 // `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`, and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
148 public static boolean darkTheme;
150 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
151 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onCreateHomeScreenShortcutCreate()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `applyDomainSettings()`.
152 public static Bitmap favoriteIconBitmap;
154 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
155 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
156 public static String formattedUrlString;
158 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
159 public static SslCertificate sslCertificate;
161 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
162 public static String orbotStatus;
164 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
165 public static String webViewTitle;
167 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
168 public static boolean displayWebpageImagesBoolean;
170 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
171 public static boolean reloadOnRestart;
173 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
174 public static boolean loadUrlOnRestart;
176 // `restartFromBookmarksActivity` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onRestart()`.
177 public static boolean restartFromBookmarksActivity;
179 // `currentBookmarksFolder` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onBackPressed()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and
180 // `loadBookmarksFolder()`.
181 public static String currentBookmarksFolder;
183 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
184 public static int domainSettingsDatabaseId;
185 public static String pinnedDomainSslIssuedToCNameString;
186 public static String pinnedDomainSslIssuedToONameString;
187 public static String pinnedDomainSslIssuedToUNameString;
188 public static String pinnedDomainSslIssuedByCNameString;
189 public static String pinnedDomainSslIssuedByONameString;
190 public static String pinnedDomainSslIssuedByUNameString;
191 public static Date pinnedDomainSslStartDate;
192 public static Date pinnedDomainSslEndDate;
195 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
196 private ActionBar appBar;
198 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
199 private boolean navigatingHistory;
201 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
202 private Bitmap favoriteIconDefaultBitmap;
204 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, `onBackPressed()`, and `onRestart()`.
205 private DrawerLayout drawerLayout;
207 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
208 private CoordinatorLayout rootCoordinatorLayout;
210 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
211 // `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
212 private WebView mainWebView;
214 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
215 private FrameLayout fullScreenVideoFrameLayout;
217 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
218 private SwipeRefreshLayout swipeRefreshLayout;
220 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
221 private RelativeLayout urlAppBarRelativeLayout;
223 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
224 private ImageView favoriteIconImageView;
226 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
227 private CookieManager cookieManager;
229 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
230 private final Map<String, String> customHeaders = new HashMap<>();
232 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
233 private boolean javaScriptEnabled;
235 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
236 private boolean firstPartyCookiesEnabled;
238 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
239 private boolean thirdPartyCookiesEnabled;
241 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
242 private boolean domStorageEnabled;
244 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
245 private boolean saveFormDataEnabled;
247 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
248 private boolean nightMode;
250 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
251 private boolean swipeToRefreshEnabled;
253 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
254 private String homepage;
256 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
257 private String searchURL;
259 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
260 private boolean adBlockerEnabled;
262 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
263 private Runtime privacyBrowserRuntime;
265 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
266 private boolean incognitoModeEnabled;
268 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
269 private boolean fullScreenBrowsingModeEnabled;
271 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
272 private boolean inFullScreenBrowsingMode;
274 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
275 private boolean hideSystemBarsOnFullscreen;
277 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
278 private boolean translucentNavigationBarOnFullscreen;
280 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
281 private String currentDomainName;
283 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
284 private boolean ignorePinnedSslCertificate;
286 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
287 private boolean waitingForOrbot;
289 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
290 private boolean domainSettingsApplied;
292 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
293 private int displayWebpageImagesInt;
295 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
296 private boolean onTheFlyDisplayImagesSet;
298 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
299 private String waitingForOrbotHTMLString;
301 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
302 private String privateDataDirectoryString;
304 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
305 private LinearLayout findOnPageLinearLayout;
307 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
308 private EditText findOnPageEditText;
310 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
311 private Menu mainMenu;
313 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
314 private ActionBarDrawerToggle drawerToggle;
316 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
317 private Toolbar supportAppBar;
319 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
320 private EditText urlTextBox;
322 // `redColorSpan` is used in `onCreate()` and `highlightUrlText()`.
323 private ForegroundColorSpan redColorSpan;
325 // `initialGrayColorSpan` is sued in `onCreate()` and `highlightUrlText()`.
326 private ForegroundColorSpan initialGrayColorSpan;
328 // `finalGrayColorSpam` is used in `onCreate()` and `highlightUrlText()`.
329 private ForegroundColorSpan finalGrayColorSpan;
331 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
334 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
335 private SslErrorHandler sslErrorHandler;
337 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
338 private static HttpAuthHandler httpAuthHandler;
340 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
341 private InputMethodManager inputMethodManager;
343 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
344 private RelativeLayout mainWebViewRelativeLayout;
346 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
347 private boolean urlIsLoading;
349 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
350 private boolean pinnedDomainSslCertificate;
352 // `bookmarksDatabaseHelper` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
353 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
355 // `bookmarksListView` is used in `onCreate()`, `onCreateBookmark()`, `onCreateBookmarkFolder()`, and `loadBookmarksFolder()`.
356 private ListView bookmarksListView;
358 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
359 private TextView bookmarksTitleTextView;
361 // `bookmarksCursor` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()`, `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
362 private Cursor bookmarksCursor;
364 // `bookmarksCursorAdapter` is used in `onCreateBookmark()`, `onCreateBookmarkFolder()` `onSaveEditBookmark()`, `onSaveEditBookmarkFolder()`, and `loadBookmarksFolder()`.
365 private CursorAdapter bookmarksCursorAdapter;
367 // `oldFolderNameString` is used in `onCreate()` and `onSaveEditBookmarkFolder()`.
368 private String oldFolderNameString;
371 // 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.
372 @SuppressLint("SetJavaScriptEnabled")
373 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
374 @SuppressWarnings("deprecation")
375 protected void onCreate(Bundle savedInstanceState) {
376 // Get a handle for `sharedPreferences`. `this` references the current context.
377 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
379 // Get the theme preference.
380 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
382 // Set the activity theme.
384 setTheme(R.style.PrivacyBrowserDark);
386 setTheme(R.style.PrivacyBrowserLight);
389 // Run the default commands.
390 super.onCreate(savedInstanceState);
392 // Set the content view.
393 setContentView(R.layout.main_drawerlayout);
395 // Get a handle for `inputMethodManager`.
396 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
398 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
399 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
400 setSupportActionBar(supportAppBar);
401 appBar = getSupportActionBar();
403 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
404 assert appBar != null;
406 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
407 appBar.setCustomView(R.layout.url_app_bar);
408 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
410 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
411 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
412 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
413 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
415 // Get a handle for `urlTextBox`.
416 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
418 // Remove the formatting from `urlTextBar` when the user is editing the text.
419 urlTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
421 public void onFocusChange(View v, boolean hasFocus) {
422 if (hasFocus) { // The user is editing `urlTextBox`.
423 // Remove the highlighting.
424 urlTextBox.getText().removeSpan(redColorSpan);
425 urlTextBox.getText().removeSpan(initialGrayColorSpan);
426 urlTextBox.getText().removeSpan(finalGrayColorSpan);
427 } else { // The user has stopped editing `urlTextBox`.
428 // Reapply the highlighting.
434 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
435 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
437 public boolean onKey(View v, int keyCode, KeyEvent event) {
438 // If the event is a key-down event on the `enter` button, load the URL.
439 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
440 // Load the URL into the mainWebView and consume the event.
442 loadUrlFromTextBox();
443 } catch (UnsupportedEncodingException e) {
446 // If the enter key was pressed, consume the event.
449 // If any other key was pressed, do not consume the event.
455 // Set `waitingForOrbotHTMLString`.
456 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
458 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
459 currentDomainName = "";
460 orbotStatus = "unknown";
461 waitingForOrbot = false;
463 // Create an Orbot status `BroadcastReceiver`.
464 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
466 public void onReceive(Context context, Intent intent) {
467 // Store the content of the status message in `orbotStatus`.
468 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
470 // If we are waiting on Orbot, load the website now that Orbot is connected.
471 if (orbotStatus.equals("ON") && waitingForOrbot) {
472 // Reset `waitingForOrbot`.
473 waitingForOrbot = false;
475 // Load `formattedUrlString
476 loadUrl(formattedUrlString);
481 // Register `orbotStatusBroadcastReceiver` on `this` context.
482 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
484 // Get handles for views that need to be accessed.
485 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
486 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
487 bookmarksListView = (ListView) findViewById(R.id.bookmarks_drawer_listview);
488 bookmarksTitleTextView = (TextView) findViewById(R.id.bookmarks_title_textview);
489 FloatingActionButton launchBookmarksActivityFab = (FloatingActionButton) findViewById(R.id.launch_bookmarks_activity_fab);
490 FloatingActionButton createBookmarkFolderFab = (FloatingActionButton) findViewById(R.id.create_bookmark_folder_fab);
491 FloatingActionButton createBookmarkFab = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
492 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
493 mainWebView = (WebView) findViewById(R.id.main_webview);
494 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
495 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
496 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
497 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
498 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
500 // 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.
502 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_dark));
503 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
504 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
505 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
507 launchBookmarksActivityFab.setImageDrawable(getResources().getDrawable(R.drawable.bookmarks_light));
508 createBookmarkFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
509 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
510 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
513 // Set the launch bookmarks activity FAB to launch the bookmarks activity.
514 launchBookmarksActivityFab.setOnClickListener(new View.OnClickListener() {
516 public void onClick(View v) {
517 // Create an intent to launch the bookmarks activity.
518 Intent bookmarksIntent = new Intent(getApplicationContext(), BookmarksActivity.class);
520 // Include the current folder with the `Intent`.
521 bookmarksIntent.putExtra("Current Folder", currentBookmarksFolder);
524 startActivity(bookmarksIntent);
528 // Set the create new bookmark folder FAB to display the `AlertDialog`.
529 createBookmarkFolderFab.setOnClickListener(new View.OnClickListener() {
531 public void onClick(View v) {
532 // Show the `CreateBookmarkFolderDialog` `AlertDialog` and name the instance `@string/create_folder`.
533 AppCompatDialogFragment createBookmarkFolderDialog = new CreateBookmarkFolderDialog();
534 createBookmarkFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_folder));
538 // Set the create new bookmark FAB to display the `AlertDialog`.
539 createBookmarkFab.setOnClickListener(new View.OnClickListener() {
541 public void onClick(View view) {
542 // Show the `CreateBookmarkDialog` `AlertDialog` and name the instance `@string/create_bookmark`.
543 AppCompatDialogFragment createBookmarkDialog = new CreateBookmarkDialog();
544 createBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.create_bookmark));
548 // Create a double-tap listener to toggle full-screen mode.
549 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
550 // Override `onDoubleTap()`. All other events are handled using the default settings.
552 public boolean onDoubleTap(MotionEvent event) {
553 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
554 // Toggle `inFullScreenBrowsingMode`.
555 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
557 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
558 // Hide the `appBar`.
561 // Hide the `BannerAd` in the free flavor.
562 if (BuildConfig.FLAVOR.contentEquals("free")) {
563 BannerAd.hideAd(adView);
566 // Modify the system bars.
567 if (hideSystemBarsOnFullscreen) { // Hide everything.
568 // Remove the translucent overlays.
569 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
571 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
572 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
574 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
575 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
576 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
578 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
580 // Set `rootCoordinatorLayout` to fill the whole screen.
581 rootCoordinatorLayout.setFitsSystemWindows(false);
582 } else { // Hide everything except the status and navigation bars.
583 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
584 rootCoordinatorLayout.setFitsSystemWindows(false);
586 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.
587 // Set the navigation bar to be translucent.
588 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
591 } else { // Switch to normal viewing mode.
592 // Show the `appBar`.
595 // Show the `BannerAd` in the free flavor.
596 if (BuildConfig.FLAVOR.contentEquals("free")) {
597 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
598 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
600 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
601 adView = findViewById(R.id.adview);
604 // Remove the translucent navigation bar flag if it is set.
605 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
607 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
608 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
610 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
611 rootCoordinatorLayout.setSystemUiVisibility(0);
613 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
614 rootCoordinatorLayout.setFitsSystemWindows(true);
617 // Consume the double-tap.
619 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
625 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
626 mainWebView.setOnTouchListener(new View.OnTouchListener() {
628 public boolean onTouch(View v, MotionEvent event) {
629 // Send the `event` to `gestureDetector`.
630 return gestureDetector.onTouchEvent(event);
634 // Update `findOnPageCountTextView`.
635 mainWebView.setFindListener(new WebView.FindListener() {
636 // Get a handle for `findOnPageCountTextView`.
637 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
640 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
641 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
642 // Set `findOnPageCountTextView` to `0/0`.
643 findOnPageCountTextView.setText(R.string.zero_of_zero);
644 } else if (isDoneCounting) { // There are matches.
645 // `activeMatchOrdinal` is zero-based.
646 int activeMatch = activeMatchOrdinal + 1;
648 // Set `findOnPageCountTextView`.
649 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
654 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
655 findOnPageEditText.addTextChangedListener(new TextWatcher() {
657 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
662 public void onTextChanged(CharSequence s, int start, int before, int count) {
667 public void afterTextChanged(Editable s) {
668 // Search for the text in `mainWebView`.
669 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
673 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
674 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
676 public boolean onKey(View v, int keyCode, KeyEvent event) {
677 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
678 // Hide the soft keyboard. `0` indicates no additional flags.
679 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
681 // Consume the event.
683 } else { // A different key was pressed.
684 // Do not consume the event.
690 // Implement swipe to refresh
691 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
692 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
693 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
695 public void onRefresh() {
696 mainWebView.reload();
700 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
701 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
702 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
704 // Listen for touches on the navigation menu.
705 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
706 navigationView.setNavigationItemSelectedListener(this);
708 // 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.
709 final Menu navigationMenu = navigationView.getMenu();
710 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
711 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
712 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
714 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
715 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
716 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
718 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
719 currentBookmarksFolder = "";
721 // Load the home folder, which is `""` in the database.
722 loadBookmarksFolder();
724 bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
726 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
727 // Convert the id from long to int to match the format of the bookmarks database.
728 int databaseID = (int) id;
730 // Get the bookmark `Cursor` for this ID and move it to the first row.
731 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
732 bookmarkCursor.moveToFirst();
734 // Act upon the bookmark according to the type.
735 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
736 // Store the new folder name in `currentBookmarksFolder`.
737 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
739 // Load the new folder.
740 loadBookmarksFolder();
741 } else { // The selected bookmark is not a folder.
742 // Load the bookmark URL.
743 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
745 // Close the bookmarks drawer.
746 drawerLayout.closeDrawer(GravityCompat.END);
749 // Close the `Cursor`.
750 bookmarkCursor.close();
754 bookmarksListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
756 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
757 // Convert the database ID from `long` to `int`.
758 int databaseId = (int) id;
760 // Find out if the selected bookmark is a folder.
761 boolean isFolder = bookmarksDatabaseHelper.isFolder(databaseId);
764 // Save the current folder name, which is used in `onSaveEditBookmarkFolder()`.
765 oldFolderNameString = bookmarksCursor.getString(bookmarksCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
767 // Show the edit bookmark folder `AlertDialog` and name the instance `@string/edit_folder`.
768 AppCompatDialogFragment editFolderDialog = EditBookmarkFolderDialog.folderDatabaseId(databaseId);
769 editFolderDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_folder));
771 // Show the edit bookmark `AlertDialog` and name the instance `@string/edit_bookmark`.
772 AppCompatDialogFragment editBookmarkDialog = EditBookmarkDialog.bookmarkDatabaseId(databaseId);
773 editBookmarkDialog.show(getSupportFragmentManager(), getResources().getString(R.string.edit_bookmark));
776 // Consume the event.
781 // The `DrawerListener` allows us to update the Navigation Menu.
782 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
784 public void onDrawerSlide(View drawerView, float slideOffset) {
788 public void onDrawerOpened(View drawerView) {
792 public void onDrawerClosed(View drawerView) {
796 public void onDrawerStateChanged(int newState) {
797 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
798 // Update the `Back`, `Forward`, and `History` menu items.
799 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
800 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
801 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
803 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
804 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
806 // Clear the focus from `urlTextBox` if it has it.
807 urlTextBox.clearFocus();
812 // drawerToggle creates the hamburger icon at the start of the AppBar.
813 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
815 // Initialize `adServerSet`.
816 final Set<String> adServersSet = new HashSet<>();
818 // Load the list of ad servers into memory.
820 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
821 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
823 // Create a string for storing each ad server.
826 // Populate `adServersSet`.
827 while ((adServer = bufferedReader.readLine()) != null) {
828 adServersSet.add(adServer);
831 // Close `bufferedReader`.
832 bufferedReader.close();
833 } catch (IOException ioException) {
834 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
837 mainWebView.setWebViewClient(new WebViewClient() {
838 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
839 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
840 @SuppressWarnings("deprecation")
842 public boolean shouldOverrideUrlLoading(WebView view, String url) {
843 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
844 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
845 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
847 // Parse the url and set it as the data for the `Intent`.
848 emailIntent.setData(Uri.parse(url));
850 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
851 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
854 startActivity(emailIntent);
856 // Returning `true` indicates the application is handling the URL.
858 } else { // Load the URL in Privacy Browser.
859 // Apply the domain settings for the new URL.
860 applyDomainSettings(url);
862 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
867 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
868 @SuppressWarnings("deprecation")
870 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
871 if (adBlockerEnabled) { // Block ads.
872 // Extract the host from `url`.
873 Uri requestUri = Uri.parse(url);
874 String requestHost = requestUri.getHost();
876 // Initialize a variable to track if this is an ad server.
877 boolean requestHostIsAdServer = false;
879 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
880 if (requestHost != null) {
881 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
882 if (adServersSet.contains(requestHost)) {
883 requestHostIsAdServer = true;
886 // Strip out the lowest subdomain of `requestHost`.
887 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
891 if (requestHostIsAdServer) { // It is an ad server.
892 // Return an empty `WebResourceResponse`.
893 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
894 } else { // It is not an ad server.
895 // `return null` loads the requested resource.
898 } else { // Ad blocking is disabled.
899 // `return null` loads the requested resource.
904 // Handle HTTP authentication requests.
906 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
907 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
908 httpAuthHandler = handler;
910 // Display the HTTP authentication dialog.
911 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
912 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
915 // Update the URL in urlTextBox when the page starts to load.
917 public void onPageStarted(WebView view, String url, Bitmap favicon) {
918 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
920 mainWebView.setVisibility(View.INVISIBLE);
923 // Hide the keyboard. `0` indicates no additional flags.
924 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
926 // Check to see if we are waiting on Orbot.
927 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
928 // 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.
929 formattedUrlString = url;
931 // Display the formatted URL text.
932 urlTextBox.setText(formattedUrlString);
934 // Apply text highlighting to `urlTextBox`.
937 // Apply any custom domain settings if the URL was loaded by navigating history.
938 if (navigatingHistory) {
939 applyDomainSettings(url);
942 // 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.
947 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
949 public void onPageFinished(WebView view, String url) {
950 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
951 urlIsLoading = false;
953 // Clear the cache and history if Incognito Mode is enabled.
954 if (incognitoModeEnabled) {
955 // Clear the cache. `true` includes disk files.
956 mainWebView.clearCache(true);
958 // Clear the back/forward history.
959 mainWebView.clearHistory();
961 // Manually delete cache folders.
963 // Delete the main `cache` folder.
964 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
966 // 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`.
967 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
968 } catch (IOException e) {
969 // Do nothing if an error is thrown.
973 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
974 if (!waitingForOrbot) {
975 // Check to see if `WebView` has set `url` to be `about:blank`.
976 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
977 // Set `formattedUrlString` to `""`.
978 formattedUrlString = "";
980 urlTextBox.setText(formattedUrlString);
982 // Request focus for `urlTextBox`.
983 urlTextBox.requestFocus();
985 // Display the keyboard.
986 inputMethodManager.showSoftInput(urlTextBox, 0);
988 // Apply the domain settings. This clears any settings from the previous domain.
989 applyDomainSettings(formattedUrlString);
990 } else { // `WebView` has loaded a webpage.
991 // Set `formattedUrlString`.
992 formattedUrlString = url;
994 // Only update `urlTextBox` if the user is not typing in it.
995 if (!urlTextBox.hasFocus()) {
996 // Display the formatted URL text.
997 urlTextBox.setText(formattedUrlString);
999 // Apply text highlighting to `urlTextBox`.
1004 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
1005 sslCertificate = mainWebView.getCertificate();
1007 // 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.
1008 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
1009 // Initialize the current SSL certificate variables.
1010 String currentWebsiteIssuedToCName = "";
1011 String currentWebsiteIssuedToOName = "";
1012 String currentWebsiteIssuedToUName = "";
1013 String currentWebsiteIssuedByCName = "";
1014 String currentWebsiteIssuedByOName = "";
1015 String currentWebsiteIssuedByUName = "";
1016 Date currentWebsiteSslStartDate = null;
1017 Date currentWebsiteSslEndDate = null;
1020 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
1021 if (sslCertificate != null) {
1022 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
1023 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
1024 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
1025 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
1026 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
1027 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
1028 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
1029 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
1032 // 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`.
1033 String currentWebsiteSslStartDateString = "";
1034 String currentWebsiteSslEndDateString = "";
1035 String pinnedDomainSslStartDateString = "";
1036 String pinnedDomainSslEndDateString = "";
1038 // Convert the `Dates` to `Strings` if they are not `null`.
1039 if (currentWebsiteSslStartDate != null) {
1040 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
1043 if (currentWebsiteSslEndDate != null) {
1044 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
1047 if (pinnedDomainSslStartDate != null) {
1048 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
1051 if (pinnedDomainSslEndDate != null) {
1052 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
1055 // Check to see if the pinned SSL certificate matches the current website certificate.
1056 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) || !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) ||
1057 !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) || !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
1058 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) { // The pinned SSL certificate doesn't match the current domain certificate.
1059 //Display the pinned SSL certificate mismatch `AlertDialog`.
1060 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
1061 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
1067 // Handle SSL Certificate errors.
1069 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
1070 // Get the current website SSL certificate.
1071 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
1073 // Extract the individual pieces of information from the current website SSL certificate.
1074 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
1075 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
1076 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
1077 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
1078 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
1079 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
1080 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
1081 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
1083 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1084 if (pinnedDomainSslCertificate &&
1085 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) && currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) &&
1086 currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) && currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1087 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) { // An SSL certificate is pinned and matches the current domain certificate.
1088 // Proceed to the website without displaying an error.
1090 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1091 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1092 sslErrorHandler = handler;
1094 // Display the SSL error `AlertDialog`.
1095 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1096 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1101 // Get a handle for the progress bar.
1102 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
1104 mainWebView.setWebChromeClient(new WebChromeClient() {
1105 // Update the progress bar when a page is loading.
1107 public void onProgressChanged(WebView view, int progress) {
1108 // Inject the night mode CSS if night mode is enabled.
1110 // `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.
1111 // `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.
1112 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
1113 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '" +
1114 "* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important; text-shadow: none !important; border: none !important;}" +
1115 "a {color: #1565C0 !important;}" +
1116 "'; parent.appendChild(style)})()", new ValueCallback<String>() {
1118 public void onReceiveValue(String value) {
1119 // Initialize a `Handler` to display `mainWebView`.
1120 Handler displayWebViewHandler = new Handler();
1122 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
1123 Runnable displayWebViewRunnable = new Runnable() {
1125 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
1126 if (progressBar.getVisibility() == View.GONE) {
1127 mainWebView.setVisibility(View.VISIBLE);
1132 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
1133 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
1138 progressBar.setProgress(progress);
1139 if (progress < 100) {
1140 // Show the progress bar.
1141 progressBar.setVisibility(View.VISIBLE);
1143 // Hide the progress bar.
1144 progressBar.setVisibility(View.GONE);
1146 // Display `mainWebView` if night mode is disabled.
1147 // 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.
1149 mainWebView.setVisibility(View.VISIBLE);
1152 //Stop the `SwipeToRefresh` indicator if it is running
1153 swipeRefreshLayout.setRefreshing(false);
1157 // Set the favorite icon when it changes.
1159 public void onReceivedIcon(WebView view, Bitmap icon) {
1160 // Only update the favorite icon if the website has finished loading.
1161 if (progressBar.getVisibility() == View.GONE) {
1162 // Save a copy of the favorite icon.
1163 favoriteIconBitmap = icon;
1165 // Place the favorite icon in the appBar.
1166 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1170 // Save a copy of the title when it changes.
1172 public void onReceivedTitle(WebView view, String title) {
1173 // Save a copy of the title.
1174 webViewTitle = title;
1177 // Enter full screen video
1179 public void onShowCustomView(View view, CustomViewCallback callback) {
1180 // Pause the ad if this is the free flavor.
1181 if (BuildConfig.FLAVOR.contentEquals("free")) {
1182 BannerAd.pauseAd(adView);
1185 // Remove the translucent overlays.
1186 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1188 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1189 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1191 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1192 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1193 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1195 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1197 // Set `rootCoordinatorLayout` to fill the entire screen.
1198 rootCoordinatorLayout.setFitsSystemWindows(false);
1200 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1201 fullScreenVideoFrameLayout.addView(view);
1202 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1205 // Exit full screen video
1206 public void onHideCustomView() {
1207 // Hide `fullScreenVideoFrameLayout`.
1208 fullScreenVideoFrameLayout.removeAllViews();
1209 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1211 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1212 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1214 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1215 rootCoordinatorLayout.setFitsSystemWindows(true);
1217 // Show the ad if this is the free flavor.
1218 if (BuildConfig.FLAVOR.contentEquals("free")) {
1219 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1220 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1222 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1223 adView = findViewById(R.id.adview);
1228 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1229 registerForContextMenu(mainWebView);
1231 // Allow the downloading of files.
1232 mainWebView.setDownloadListener(new DownloadListener() {
1234 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
1235 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1236 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1237 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1241 // Allow pinch to zoom.
1242 mainWebView.getSettings().setBuiltInZoomControls(true);
1244 // Hide zoom controls.
1245 mainWebView.getSettings().setDisplayZoomControls(false);
1247 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1248 mainWebView.getSettings().setUseWideViewPort(true);
1250 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1251 mainWebView.getSettings().setLoadWithOverviewMode(true);
1253 // Explicitly disable geolocation.
1254 mainWebView.getSettings().setGeolocationEnabled(false);
1256 // Initialize cookieManager.
1257 cookieManager = CookieManager.getInstance();
1259 // 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).
1260 customHeaders.put("X-Requested-With", "");
1262 // 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.
1263 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1265 // Get the intent that started the app.
1266 final Intent launchingIntent = getIntent();
1268 // Extract the launching intent data as `launchingIntentUriData`.
1269 final Uri launchingIntentUriData = launchingIntent.getData();
1271 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1272 if (launchingIntentUriData != null) {
1273 formattedUrlString = launchingIntentUriData.toString();
1276 // Get a handle for the `Runtime`.
1277 privacyBrowserRuntime = Runtime.getRuntime();
1279 // Store the application's private data directory.
1280 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`.
1282 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1283 inFullScreenBrowsingMode = false;
1285 // Initialize AdView for the free flavor.
1286 adView = findViewById(R.id.adview);
1288 // Initialize the privacy settings variables.
1289 javaScriptEnabled = false;
1290 firstPartyCookiesEnabled = false;
1291 thirdPartyCookiesEnabled = false;
1292 domStorageEnabled = false;
1293 saveFormDataEnabled = false;
1296 // Initialize `webViewTitle`.
1297 webViewTitle = getString(R.string.no_title);
1299 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1300 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1301 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1302 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1304 // If the favorite icon is null, load the default.
1305 if (favoriteIconBitmap == null) {
1306 favoriteIconBitmap = favoriteIconDefaultBitmap;
1309 // Apply the app settings from the shared preferences.
1312 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1313 if (!waitingForOrbot) {
1314 loadUrl(formattedUrlString);
1319 protected void onNewIntent(Intent intent) {
1320 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1323 if (intent.getData() != null) {
1324 // Get the intent data and convert it to a string.
1325 final Uri intentUriData = intent.getData();
1326 formattedUrlString = intentUriData.toString();
1329 // Close the navigation drawer if it is open.
1330 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1331 drawerLayout.closeDrawer(GravityCompat.START);
1334 // Load the website.
1335 loadUrl(formattedUrlString);
1337 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1338 mainWebView.requestFocus();
1342 public void onRestart() {
1345 // Apply the app settings, which may have been changed in `SettingsActivity`.
1348 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1349 updatePrivacyIcons(true);
1351 // Set the display webpage images mode.
1352 setDisplayWebpageImages();
1354 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1355 if (reloadOnRestart) {
1356 // Reload `mainWebView`.
1357 mainWebView.reload();
1359 // Reset `reloadOnRestartBoolean`.
1360 reloadOnRestart = false;
1363 // Load the URL on restart to apply changes to night mode.
1364 if (loadUrlOnRestart) {
1365 // Load the current `formattedUrlString`.
1366 loadUrl(formattedUrlString);
1368 // Reset `loadUrlOnRestart.
1369 loadUrlOnRestart = false;
1373 if (restartFromBookmarksActivity) {
1374 // Close the bookmarks drawer.
1375 drawerLayout.closeDrawer(GravityCompat.END);
1377 // Reload the bookmarks drawer.
1378 loadBookmarksFolder();
1380 // Reset `restartFromBookmarksActivity`.
1381 restartFromBookmarksActivity = false;
1385 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1387 public void onResume() {
1390 // Resume JavaScript (if enabled).
1391 mainWebView.resumeTimers();
1393 // Resume `mainWebView`.
1394 mainWebView.onResume();
1396 // Resume the adView for the free flavor.
1397 if (BuildConfig.FLAVOR.contentEquals("free")) {
1398 BannerAd.resumeAd(adView);
1403 public void onPause() {
1404 // Pause `mainWebView`.
1405 mainWebView.onPause();
1407 // Stop all JavaScript.
1408 mainWebView.pauseTimers();
1410 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1411 if (BuildConfig.FLAVOR.contentEquals("free")) {
1412 BannerAd.pauseAd(adView);
1419 public boolean onCreateOptionsMenu(Menu menu) {
1420 // Inflate the menu; this adds items to the action bar if it is present.
1421 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1423 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1426 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1427 updatePrivacyIcons(false);
1429 // Get handles for the menu items.
1430 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1431 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1432 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1433 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1435 // Only display third-party cookies if SDK >= 21
1436 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1438 // Get the shared preference values. `this` references the current context.
1439 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1441 // Set the status of the additional app bar icons. The default is `false`.
1442 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1443 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1444 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1445 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1446 } else { //Do not display the additional icons.
1447 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1448 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1449 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1456 public boolean onPrepareOptionsMenu(Menu menu) {
1457 // Get handles for the menu items.
1458 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1459 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1460 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1461 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1462 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1463 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1464 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1465 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1466 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1467 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1469 // Set the status of the menu item checkboxes.
1470 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1471 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1472 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1473 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1474 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1476 // Enable third-party cookies if first-party cookies are enabled.
1477 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1479 // Enable `DOM Storage` if JavaScript is enabled.
1480 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1482 // Enable `Clear Cookies` if there are any.
1483 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1485 // Get a count of the number of files in the `Local Storage` directory.
1486 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1487 int localStorageDirectoryNumberOfFiles = 0;
1488 if (localStorageDirectory.exists()) {
1489 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1492 // Get a count of the number of files in the `IndexedDB` directory.
1493 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1494 int indexedDBDirectoryNumberOfFiles = 0;
1495 if (indexedDBDirectory.exists()) {
1496 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1499 // Enable `Clear DOM Storage` if there is any.
1500 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1502 // Enable `Clear Form Data` is there is any.
1503 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1504 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1506 // Initialize font size variables.
1507 int fontSize = mainWebView.getSettings().getTextZoom();
1508 String fontSizeTitle;
1509 MenuItem selectedFontSizeMenuItem;
1511 // Prepare the font size title and current size menu item.
1514 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1515 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1519 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1520 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1524 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1525 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1529 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1530 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1534 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1535 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1539 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1540 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1544 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1545 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1549 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1550 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1554 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1555 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1559 // Set the font size title and select the current size menu item.
1560 fontSizeMenuItem.setTitle(fontSizeTitle);
1561 selectedFontSizeMenuItem.setChecked(true);
1563 // Only show `Refresh` if `swipeToRefresh` is disabled.
1564 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1566 // Run all the other default commands.
1567 super.onPrepareOptionsMenu(menu);
1569 // `return true` displays the menu.
1574 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1575 @SuppressLint("SetJavaScriptEnabled")
1576 // removeAllCookies is deprecated, but it is required for API < 21.
1577 @SuppressWarnings("deprecation")
1578 public boolean onOptionsItemSelected(MenuItem menuItem) {
1579 int menuItemId = menuItem.getItemId();
1581 // Set the commands that relate to the menu entries.
1582 switch (menuItemId) {
1583 case R.id.toggle_javascript:
1584 // Switch the status of javaScriptEnabled.
1585 javaScriptEnabled = !javaScriptEnabled;
1587 // Apply the new JavaScript status.
1588 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1590 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1591 updatePrivacyIcons(true);
1593 // Display a `Snackbar`.
1594 if (javaScriptEnabled) { // JavaScrip is enabled.
1595 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1596 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1597 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1598 } else { // Privacy mode.
1599 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1602 // Reload the WebView.
1603 mainWebView.reload();
1606 case R.id.toggle_first_party_cookies:
1607 // Switch the status of firstPartyCookiesEnabled.
1608 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1610 // Update the menu checkbox.
1611 menuItem.setChecked(firstPartyCookiesEnabled);
1613 // Apply the new cookie status.
1614 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1616 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1617 updatePrivacyIcons(true);
1619 // Display a `Snackbar`.
1620 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1621 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1622 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1623 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1624 } else { // Privacy mode.
1625 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1628 // Reload the WebView.
1629 mainWebView.reload();
1632 case R.id.toggle_third_party_cookies:
1633 if (Build.VERSION.SDK_INT >= 21) {
1634 // Switch the status of thirdPartyCookiesEnabled.
1635 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1637 // Update the menu checkbox.
1638 menuItem.setChecked(thirdPartyCookiesEnabled);
1640 // Apply the new cookie status.
1641 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1643 // Display a `Snackbar`.
1644 if (thirdPartyCookiesEnabled) {
1645 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1647 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1650 // Reload the WebView.
1651 mainWebView.reload();
1652 } // Else do nothing because SDK < 21.
1655 case R.id.toggle_dom_storage:
1656 // Switch the status of domStorageEnabled.
1657 domStorageEnabled = !domStorageEnabled;
1659 // Update the menu checkbox.
1660 menuItem.setChecked(domStorageEnabled);
1662 // Apply the new DOM Storage status.
1663 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1665 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1666 updatePrivacyIcons(true);
1668 // Display a `Snackbar`.
1669 if (domStorageEnabled) {
1670 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1672 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1675 // Reload the WebView.
1676 mainWebView.reload();
1679 case R.id.toggle_save_form_data:
1680 // Switch the status of saveFormDataEnabled.
1681 saveFormDataEnabled = !saveFormDataEnabled;
1683 // Update the menu checkbox.
1684 menuItem.setChecked(saveFormDataEnabled);
1686 // Apply the new form data status.
1687 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1689 // Display a `Snackbar`.
1690 if (saveFormDataEnabled) {
1691 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1693 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1696 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1697 updatePrivacyIcons(true);
1699 // Reload the WebView.
1700 mainWebView.reload();
1703 case R.id.clear_cookies:
1704 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1705 .setAction(R.string.undo, new View.OnClickListener() {
1707 public void onClick(View v) {
1708 // Do nothing because everything will be handled by `onDismissed()` below.
1711 .addCallback(new Snackbar.Callback() {
1713 public void onDismissed(Snackbar snackbar, int event) {
1715 // The user pushed the `Undo` button.
1716 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1720 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1722 // `cookieManager.removeAllCookie()` varies by SDK.
1723 if (Build.VERSION.SDK_INT < 21) {
1724 cookieManager.removeAllCookie();
1726 // `null` indicates no callback.
1727 cookieManager.removeAllCookies(null);
1735 case R.id.clear_dom_storage:
1736 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1737 .setAction(R.string.undo, new View.OnClickListener() {
1739 public void onClick(View v) {
1740 // Do nothing because everything will be handled by `onDismissed()` below.
1743 .addCallback(new Snackbar.Callback() {
1745 public void onDismissed(Snackbar snackbar, int event) {
1747 // The user pushed the `Undo` button.
1748 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1752 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1754 // Delete the DOM Storage.
1755 WebStorage webStorage = WebStorage.getInstance();
1756 webStorage.deleteAllData();
1758 // Manually remove `IndexedDB` if it exists.
1760 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1761 } catch (IOException e) {
1762 // Do nothing if an error is thrown.
1770 case R.id.clear_form_data:
1771 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1772 .setAction(R.string.undo, new View.OnClickListener() {
1774 public void onClick(View v) {
1775 // Do nothing because everything will be handled by `onDismissed()` below.
1778 .addCallback(new Snackbar.Callback() {
1780 public void onDismissed(Snackbar snackbar, int event) {
1782 // The user pushed the `Undo` button.
1783 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1787 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1789 // Delete the form data.
1790 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1791 mainWebViewDatabase.clearFormData();
1798 case R.id.font_size_twenty_five_percent:
1799 mainWebView.getSettings().setTextZoom(25);
1802 case R.id.font_size_fifty_percent:
1803 mainWebView.getSettings().setTextZoom(50);
1806 case R.id.font_size_seventy_five_percent:
1807 mainWebView.getSettings().setTextZoom(75);
1810 case R.id.font_size_one_hundred_percent:
1811 mainWebView.getSettings().setTextZoom(100);
1814 case R.id.font_size_one_hundred_twenty_five_percent:
1815 mainWebView.getSettings().setTextZoom(125);
1818 case R.id.font_size_one_hundred_fifty_percent:
1819 mainWebView.getSettings().setTextZoom(150);
1822 case R.id.font_size_one_hundred_seventy_five_percent:
1823 mainWebView.getSettings().setTextZoom(175);
1826 case R.id.font_size_two_hundred_percent:
1827 mainWebView.getSettings().setTextZoom(200);
1830 case R.id.display_images:
1831 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1832 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1833 mainWebView.reload();
1834 } else { // Images are not currently loaded automatically.
1835 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1838 // Set `onTheFlyDisplayImagesSet`.
1839 onTheFlyDisplayImagesSet = true;
1843 // Setup the share string.
1844 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1846 // Create the share intent.
1847 Intent shareIntent = new Intent();
1848 shareIntent.setAction(Intent.ACTION_SEND);
1849 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1850 shareIntent.setType("text/plain");
1853 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1856 case R.id.find_on_page:
1857 // Hide the URL app bar.
1858 supportAppBar.setVisibility(View.GONE);
1860 // Show the Find on Page `RelativeLayout`.
1861 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1863 // 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
1864 findOnPageEditText.postDelayed(new Runnable() {
1868 // Set the focus on `findOnPageEditText`.
1869 findOnPageEditText.requestFocus();
1871 // Display the keyboard. `0` sets no input flags.
1872 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1878 // Get a `PrintManager` instance.
1879 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1881 // Convert `mainWebView` to `printDocumentAdapter`.
1882 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1884 // Print the document. The print attributes are `null`.
1885 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1888 case R.id.add_to_homescreen:
1889 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1890 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1891 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1893 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1897 mainWebView.reload();
1901 // Don't consume the event.
1902 return super.onOptionsItemSelected(menuItem);
1906 // removeAllCookies is deprecated, but it is required for API < 21.
1907 @SuppressWarnings("deprecation")
1909 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1910 int menuItemId = menuItem.getItemId();
1912 switch (menuItemId) {
1918 if (mainWebView.canGoBack()) {
1919 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1920 navigatingHistory = true;
1922 // Load the previous website in the history.
1923 mainWebView.goBack();
1928 if (mainWebView.canGoForward()) {
1929 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1930 navigatingHistory = true;
1932 // Load the next website in the history.
1933 mainWebView.goForward();
1938 // Get the `WebBackForwardList`.
1939 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1941 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1942 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1943 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1946 case R.id.downloads:
1947 // Launch the system Download Manager.
1948 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1950 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1951 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1953 startActivity(downloadManagerIntent);
1957 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1958 currentDomainName = "";
1960 // Launch `DomainsActivity`.
1961 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1962 startActivity(domainsIntent);
1966 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1967 currentDomainName = "";
1969 // Launch `SettingsActivity`.
1970 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1971 startActivity(settingsIntent);
1975 // Launch `GuideActivity`.
1976 Intent guideIntent = new Intent(this, GuideActivity.class);
1977 startActivity(guideIntent);
1981 // Launch `AboutActivity`.
1982 Intent aboutIntent = new Intent(this, AboutActivity.class);
1983 startActivity(aboutIntent);
1986 case R.id.clearAndExit:
1987 // Get a handle for `sharedPreferences`. `this` references the current context.
1988 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1990 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1993 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1994 // The command to remove cookies changed slightly in API 21.
1995 if (Build.VERSION.SDK_INT >= 21) {
1996 cookieManager.removeAllCookies(null);
1998 cookieManager.removeAllCookie();
2001 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2003 // We have to use two commands because `Runtime.exec()` does not like `*`.
2004 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
2005 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
2006 } catch (IOException e) {
2007 // Do nothing if an error is thrown.
2011 // Clear DOM storage.
2012 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
2013 // Ask `WebStorage` to clear the DOM storage.
2014 WebStorage webStorage = WebStorage.getInstance();
2015 webStorage.deleteAllData();
2017 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2019 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2020 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
2022 // We have to use multiple commands because `Runtime.exec()` does not like `*`.
2023 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
2024 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
2025 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
2026 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
2027 } catch (IOException e) {
2028 // Do nothing if an error is thrown.
2033 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
2034 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
2035 webViewDatabase.clearFormData();
2037 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
2039 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
2040 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
2041 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
2042 } catch (IOException e) {
2043 // Do nothing if an error is thrown.
2048 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
2049 // `true` includes disk files.
2050 mainWebView.clearCache(true);
2052 // Manually delete the cache directories.
2054 // Delete the main cache directory.
2055 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
2057 // 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.
2058 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
2059 } catch (IOException e) {
2060 // Do nothing if an error is thrown.
2064 // Clear SSL certificate preferences.
2065 mainWebView.clearSslPreferences();
2067 // Clear the back/forward history.
2068 mainWebView.clearHistory();
2070 // Clear `formattedUrlString`.
2071 formattedUrlString = null;
2073 // Clear `customHeaders`.
2074 customHeaders.clear();
2076 // Detach all views from `mainWebViewRelativeLayout`.
2077 mainWebViewRelativeLayout.removeAllViews();
2079 // Destroy the internal state of `mainWebView`.
2080 mainWebView.destroy();
2082 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
2083 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
2084 if (clearEverything) {
2086 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
2087 } catch (IOException e) {
2088 // Do nothing if an error is thrown.
2092 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2093 if (Build.VERSION.SDK_INT >= 21) {
2094 finishAndRemoveTask();
2099 // Remove the terminated program from RAM. The status code is `0`.
2104 // Close the navigation drawer.
2105 drawerLayout.closeDrawer(GravityCompat.START);
2110 public void onPostCreate(Bundle savedInstanceState) {
2111 super.onPostCreate(savedInstanceState);
2113 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2114 drawerToggle.syncState();
2118 public void onConfigurationChanged(Configuration newConfig) {
2119 super.onConfigurationChanged(newConfig);
2121 // Reload the ad for the free flavor if we are not in full screen mode.
2122 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2124 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2126 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2127 adView = findViewById(R.id.adview);
2130 // `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
2131 // ActivityCompat.invalidateOptionsMenu(this);
2135 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2136 // Store the `HitTestResult`.
2137 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2140 final String imageUrl;
2141 final String linkUrl;
2143 // Get a handle for the `ClipboardManager`.
2144 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2146 switch (hitTestResult.getType()) {
2147 // `SRC_ANCHOR_TYPE` is a link.
2148 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2149 // Get the target URL.
2150 linkUrl = hitTestResult.getExtra();
2152 // Set the target URL as the title of the `ContextMenu`.
2153 menu.setHeaderTitle(linkUrl);
2155 // Add a `Load URL` entry.
2156 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2158 public boolean onMenuItemClick(MenuItem item) {
2164 // Add a `Copy URL` entry.
2165 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2167 public boolean onMenuItemClick(MenuItem item) {
2168 // Save the link URL in a `ClipData`.
2169 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2171 // Set the `ClipData` as the clipboard's primary clip.
2172 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2177 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2178 menu.add(R.string.cancel);
2181 case WebView.HitTestResult.EMAIL_TYPE:
2182 // Get the target URL.
2183 linkUrl = hitTestResult.getExtra();
2185 // Set the target URL as the title of the `ContextMenu`.
2186 menu.setHeaderTitle(linkUrl);
2188 // Add a `Write Email` entry.
2189 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2191 public boolean onMenuItemClick(MenuItem item) {
2192 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2193 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2195 // Parse the url and set it as the data for the `Intent`.
2196 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2198 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2199 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2202 startActivity(emailIntent);
2207 // Add a `Copy Email Address` entry.
2208 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2210 public boolean onMenuItemClick(MenuItem item) {
2211 // Save the email address in a `ClipData`.
2212 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2214 // Set the `ClipData` as the clipboard's primary clip.
2215 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2220 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2221 menu.add(R.string.cancel);
2224 // `IMAGE_TYPE` is an image.
2225 case WebView.HitTestResult.IMAGE_TYPE:
2226 // Get the image URL.
2227 imageUrl = hitTestResult.getExtra();
2229 // Set the image URL as the title of the `ContextMenu`.
2230 menu.setHeaderTitle(imageUrl);
2232 // Add a `View Image` entry.
2233 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2235 public boolean onMenuItemClick(MenuItem item) {
2241 // Add a `Download Image` entry.
2242 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2244 public boolean onMenuItemClick(MenuItem item) {
2245 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2246 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2247 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2252 // Add a `Copy URL` entry.
2253 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2255 public boolean onMenuItemClick(MenuItem item) {
2256 // Save the image URL in a `ClipData`.
2257 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2259 // Set the `ClipData` as the clipboard's primary clip.
2260 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2265 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2266 menu.add(R.string.cancel);
2270 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2271 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2272 // Get the image URL.
2273 imageUrl = hitTestResult.getExtra();
2275 // Set the image URL as the title of the `ContextMenu`.
2276 menu.setHeaderTitle(imageUrl);
2278 // Add a `View Image` entry.
2279 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2281 public boolean onMenuItemClick(MenuItem item) {
2287 // Add a `Download Image` entry.
2288 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2290 public boolean onMenuItemClick(MenuItem item) {
2291 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2292 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2293 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2298 // Add a `Copy URL` entry.
2299 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2301 public boolean onMenuItemClick(MenuItem item) {
2302 // Save the image URL in a `ClipData`.
2303 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2305 // Set the `ClipData` as the clipboard's primary clip.
2306 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2311 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2312 menu.add(R.string.cancel);
2318 public void onCreateBookmark(AppCompatDialogFragment dialogFragment) {
2319 // Get the `EditTexts` from the `dialogFragment`.
2320 EditText createBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_name_edittext);
2321 EditText createBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_bookmark_url_edittext);
2323 // Extract the strings from the `EditTexts`.
2324 String bookmarkNameString = createBookmarkNameEditText.getText().toString();
2325 String bookmarkUrlString = createBookmarkUrlEditText.getText().toString();
2327 // Convert the favoriteIcon Bitmap to a byte array. `0` is for lossless compression (the only option for a PNG).
2328 ByteArrayOutputStream favoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2329 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, favoriteIconByteArrayOutputStream);
2330 byte[] favoriteIconByteArray = favoriteIconByteArrayOutputStream.toByteArray();
2332 // Display the new bookmark below the current items in the (0 indexed) list.
2333 int newBookmarkDisplayOrder = bookmarksListView.getCount();
2335 // Create the bookmark.
2336 bookmarksDatabaseHelper.createBookmark(bookmarkNameString, bookmarkUrlString, newBookmarkDisplayOrder, currentBookmarksFolder, favoriteIconByteArray);
2338 // Update `bookmarksCursor` with the current contents of this folder.
2339 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2341 // Update the `ListView`.
2342 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2344 // Scroll to the new bookmark.
2345 bookmarksListView.setSelection(newBookmarkDisplayOrder);
2349 public void onCreateBookmarkFolder(AppCompatDialogFragment dialogFragment) {
2350 // Get handles for the views in `dialogFragment`.
2351 EditText createFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.create_folder_name_edittext);
2352 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon_radiobutton);
2353 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.create_folder_default_icon);
2355 // Get new folder name string.
2356 String folderNameString = createFolderNameEditText.getText().toString();
2358 // Get the new folder icon `Bitmap`.
2359 Bitmap folderIconBitmap;
2360 if (defaultFolderIconRadioButton.isChecked()) { // Use the default folder icon.
2361 // Get the default folder icon and convert it to a `Bitmap`.
2362 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2363 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2364 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2365 } else { // Use the `WebView` favorite icon.
2366 folderIconBitmap = favoriteIconBitmap;
2369 // Convert `folderIconBitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2370 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2371 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2372 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2374 // Move all the bookmarks down one in the display order.
2375 for (int i = 0; i < bookmarksListView.getCount(); i++) {
2376 int databaseId = (int) bookmarksListView.getItemIdAtPosition(i);
2377 bookmarksDatabaseHelper.updateDisplayOrder(databaseId, i + 1);
2380 // Create the folder, placing it at the top of the ListView
2381 bookmarksDatabaseHelper.createFolder(folderNameString, 0, currentBookmarksFolder, folderIconByteArray);
2383 // Update `bookmarksCursor` with the current contents of this folder.
2384 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2386 // Update the `ListView`.
2387 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2389 // Scroll to the new folder.
2390 bookmarksListView.setSelection(0);
2394 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2395 // Get shortcutNameEditText from the alert dialog.
2396 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2398 // Create the bookmark shortcut based on formattedUrlString.
2399 Intent bookmarkShortcut = new Intent();
2400 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
2401 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
2403 // Place the bookmark shortcut on the home screen.
2404 Intent placeBookmarkShortcut = new Intent();
2405 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
2406 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
2407 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
2408 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
2409 sendBroadcast(placeBookmarkShortcut);
2413 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2414 // Download the image if it has an HTTP or HTTPS URI.
2415 if (imageUrl.startsWith("http")) {
2416 // Get a handle for the system `DOWNLOAD_SERVICE`.
2417 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2419 // Parse `imageUrl`.
2420 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2422 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2423 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2424 if (firstPartyCookiesEnabled) {
2425 // Get the cookies for `imageUrl`.
2426 String cookies = cookieManager.getCookie(imageUrl);
2428 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2429 downloadRequest.addRequestHeader("Cookie", cookies);
2432 // Get the file name from `dialogFragment`.
2433 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
2434 String imageName = downloadImageNameEditText.getText().toString();
2436 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2437 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2438 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2439 } else { // Only set the title using `imageName`.
2440 downloadRequest.setTitle(imageName);
2443 // Allow `MediaScanner` to index the download if it is a media file.
2444 downloadRequest.allowScanningByMediaScanner();
2446 // Add the URL as the description for the download.
2447 downloadRequest.setDescription(imageUrl);
2449 // Show the download notification after the download is completed.
2450 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2452 // Initiate the download.
2453 downloadManager.enqueue(downloadRequest);
2454 } else { // The image is not an HTTP or HTTPS URI.
2455 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2460 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2461 // Download the file if it has an HTTP or HTTPS URI.
2462 if (downloadUrl.startsWith("http")) {
2464 // Get a handle for the system `DOWNLOAD_SERVICE`.
2465 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2467 // Parse `downloadUrl`.
2468 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2470 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2471 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2472 if (firstPartyCookiesEnabled) {
2473 // Get the cookies for `downloadUrl`.
2474 String cookies = cookieManager.getCookie(downloadUrl);
2476 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2477 downloadRequest.addRequestHeader("Cookie", cookies);
2480 // Get the file name from `dialogFragment`.
2481 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2482 String fileName = downloadFileNameEditText.getText().toString();
2484 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2485 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2486 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2487 } else { // Only set the title using `fileName`.
2488 downloadRequest.setTitle(fileName);
2491 // Allow `MediaScanner` to index the download if it is a media file.
2492 downloadRequest.allowScanningByMediaScanner();
2494 // Add the URL as the description for the download.
2495 downloadRequest.setDescription(downloadUrl);
2497 // Show the download notification after the download is completed.
2498 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2500 // Initiate the download.
2501 downloadManager.enqueue(downloadRequest);
2502 } else { // The download is not an HTTP or HTTPS URI.
2503 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2508 public void onSaveEditBookmark(AppCompatDialogFragment dialogFragment, int selectedBookmarkDatabaseId) {
2509 // Get handles for the views from `dialogFragment`.
2510 EditText editBookmarkNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_name_edittext);
2511 EditText editBookmarkUrlEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_url_edittext);
2512 RadioButton currentBookmarkIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_bookmark_current_icon_radiobutton);
2514 // Store the bookmark strings.
2515 String bookmarkNameString = editBookmarkNameEditText.getText().toString();
2516 String bookmarkUrlString = editBookmarkUrlEditText.getText().toString();
2518 // Update the bookmark.
2519 if (currentBookmarkIconRadioButton.isChecked()) { // Update the bookmark without changing the favorite icon.
2520 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString);
2521 } else { // Update the bookmark using the `WebView` favorite icon.
2522 // Convert the favorite icon to a byte array. `0` is for lossless compression (the only option for a PNG).
2523 ByteArrayOutputStream newFavoriteIconByteArrayOutputStream = new ByteArrayOutputStream();
2524 favoriteIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, newFavoriteIconByteArrayOutputStream);
2525 byte[] newFavoriteIconByteArray = newFavoriteIconByteArrayOutputStream.toByteArray();
2527 // Update the bookmark and the favorite icon.
2528 bookmarksDatabaseHelper.updateBookmark(selectedBookmarkDatabaseId, bookmarkNameString, bookmarkUrlString, newFavoriteIconByteArray);
2531 // Update `bookmarksCursor` with the current contents of this folder.
2532 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2534 // Update the `ListView`.
2535 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2539 public void onSaveEditBookmarkFolder(AppCompatDialogFragment dialogFragment, int selectedFolderDatabaseId) {
2540 // Get handles for the views from `dialogFragment`.
2541 EditText editFolderNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.edit_folder_name_edittext);
2542 RadioButton currentFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_current_icon_radiobutton);
2543 RadioButton defaultFolderIconRadioButton = (RadioButton) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon_radiobutton);
2544 ImageView folderIconImageView = (ImageView) dialogFragment.getDialog().findViewById(R.id.edit_folder_default_icon);
2546 // Get the new folder name.
2547 String newFolderNameString = editFolderNameEditText.getText().toString();
2549 // Check if the favorite icon has changed.
2550 if (currentFolderIconRadioButton.isChecked()) { // Only the name has changed.
2551 // Update the name in the database.
2552 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString);
2553 } else if (!currentFolderIconRadioButton.isChecked() && newFolderNameString.equals(oldFolderNameString)) { // Only the icon has changed.
2554 // Get the new folder icon `Bitmap`.
2555 Bitmap folderIconBitmap;
2556 if (defaultFolderIconRadioButton.isChecked()) {
2557 // Get the default folder icon and convert it to a `Bitmap`.
2558 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2559 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2560 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2561 } else { // Use the `WebView` favorite icon.
2562 folderIconBitmap = favoriteIconBitmap;
2565 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2566 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2567 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2568 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2570 // Update the folder icon in the database.
2571 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, folderIconByteArray);
2572 } else { // The folder icon and the name have changed.
2573 // Get the new folder icon `Bitmap`.
2574 Bitmap folderIconBitmap;
2575 if (defaultFolderIconRadioButton.isChecked()) {
2576 // Get the default folder icon and convert it to a `Bitmap`.
2577 Drawable folderIconDrawable = folderIconImageView.getDrawable();
2578 BitmapDrawable folderIconBitmapDrawable = (BitmapDrawable) folderIconDrawable;
2579 folderIconBitmap = folderIconBitmapDrawable.getBitmap();
2580 } else { // Use the `WebView` favorite icon.
2581 folderIconBitmap = MainWebViewActivity.favoriteIconBitmap;
2584 // Convert the folder `Bitmap` to a byte array. `0` is for lossless compression (the only option for a PNG).
2585 ByteArrayOutputStream folderIconByteArrayOutputStream = new ByteArrayOutputStream();
2586 folderIconBitmap.compress(Bitmap.CompressFormat.PNG, 0, folderIconByteArrayOutputStream);
2587 byte[] folderIconByteArray = folderIconByteArrayOutputStream.toByteArray();
2589 // Update the folder name and icon in the database.
2590 bookmarksDatabaseHelper.updateFolder(selectedFolderDatabaseId, oldFolderNameString, newFolderNameString, folderIconByteArray);
2593 // Update `bookmarksCursor` with the current contents of this folder.
2594 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
2596 // Update the `ListView`.
2597 bookmarksCursorAdapter.changeCursor(bookmarksCursor);
2601 public void onHttpAuthenticationCancel() {
2602 // Cancel the `HttpAuthHandler`.
2603 httpAuthHandler.cancel();
2607 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2608 // Get handles for the `EditTexts`.
2609 EditText usernameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2610 EditText passwordEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2612 // Proceed with the HTTP authentication.
2613 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2616 public void viewSslCertificate(View view) {
2617 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2618 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2619 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2623 public void onSslErrorCancel() {
2624 sslErrorHandler.cancel();
2628 public void onSslErrorProceed() {
2629 sslErrorHandler.proceed();
2633 public void onSslMismatchBack() {
2634 if (mainWebView.canGoBack()) { // There is a back page in the history.
2635 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2636 navigatingHistory = true;
2639 mainWebView.goBack();
2640 } else { // There are no pages to go back to.
2641 // Load a blank page
2647 public void onSslMismatchProceed() {
2648 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2649 ignorePinnedSslCertificate = true;
2653 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2654 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2655 navigatingHistory = true;
2657 // Load the history entry.
2658 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2662 public void onClearHistory() {
2663 // Clear the history.
2664 mainWebView.clearHistory();
2667 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2669 public void onBackPressed() {
2670 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2671 // Close the navigation drawer.
2672 drawerLayout.closeDrawer(GravityCompat.START);
2673 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2674 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2675 // close the bookmarks drawer.
2676 drawerLayout.closeDrawer(GravityCompat.END);
2677 } else { // A subfolder is displayed.
2678 // Place the former parent folder in `currentFolder`.
2679 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2681 // Load the new folder.
2682 loadBookmarksFolder();
2685 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2686 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2687 navigatingHistory = true;
2690 mainWebView.goBack();
2691 } else { // There isn't anything to do in Privacy Browser.
2692 // Pass `onBackPressed()` to the system.
2693 super.onBackPressed();
2697 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2698 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2699 String unformattedUrlString = urlTextBox.getText().toString().trim();
2701 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2702 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2703 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2704 if (!unformattedUrlString.startsWith("http")) {
2705 unformattedUrlString = "http://" + unformattedUrlString;
2708 // Initialize `unformattedUrl`.
2709 URL unformattedUrl = null;
2711 // 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.
2713 unformattedUrl = new URL(unformattedUrlString);
2714 } catch (MalformedURLException e) {
2715 e.printStackTrace();
2718 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2719 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2720 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2721 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2722 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2723 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2726 Uri.Builder formattedUri = new Uri.Builder();
2727 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2729 // Decode `formattedUri` as a `String` in `UTF-8`.
2730 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2732 // Sanitize the search input and convert it to a search.
2733 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2735 // Add the base search URL.
2736 formattedUrlString = searchURL + encodedUrlString;
2739 loadUrl(formattedUrlString);
2743 private void loadUrl(String url) {
2744 // Apply any custom domain settings.
2745 applyDomainSettings(url);
2748 mainWebView.loadUrl(url, customHeaders);
2750 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2751 urlIsLoading = true;
2754 public void findPreviousOnPage(View view) {
2755 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2756 mainWebView.findNext(false);
2759 public void findNextOnPage(View view) {
2760 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2761 mainWebView.findNext(true);
2764 public void closeFindOnPage(View view) {
2765 // Delete the contents of `find_on_page_edittext`.
2766 findOnPageEditText.setText(null);
2768 // Clear the highlighted phrases.
2769 mainWebView.clearMatches();
2771 // Hide the Find on Page `RelativeLayout`.
2772 findOnPageLinearLayout.setVisibility(View.GONE);
2774 // Show the URL app bar.
2775 supportAppBar.setVisibility(View.VISIBLE);
2777 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2778 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2781 private void applyAppSettings() {
2782 // Get a handle for `sharedPreferences`. `this` references the current context.
2783 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2785 // Store the values from `sharedPreferences` in variables.
2786 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2787 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2788 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2789 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2790 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2791 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2792 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2793 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2794 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2795 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2796 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2797 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2798 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2799 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2800 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2802 // Set the homepage, search, and proxy options.
2803 if (proxyThroughOrbot) { // Set the Tor options.
2804 // Set `torHomepageString` as `homepage`.
2805 homepage = torHomepageString;
2807 // If formattedUrlString is null assign the homepage to it.
2808 if (formattedUrlString == null) {
2809 formattedUrlString = homepage;
2812 // Set the search URL.
2813 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2814 searchURL = torSearchCustomURLString;
2815 } else { // Use the string from the pre-built list.
2816 searchURL = torSearchString;
2819 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2820 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2822 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2824 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2826 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2829 // Display a message to the user if we are waiting on Orbot.
2830 if (!orbotStatus.equals("ON")) {
2831 // Set `waitingForOrbot`.
2832 waitingForOrbot = true;
2834 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2835 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2837 } else { // Set the non-Tor options.
2838 // Set `homepageString` as `homepage`.
2839 homepage = homepageString;
2841 // If formattedUrlString is null assign the homepage to it.
2842 if (formattedUrlString == null) {
2843 formattedUrlString = homepage;
2846 // Set the search URL.
2847 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2848 searchURL = searchCustomURLString;
2849 } else { // Use the string from the pre-built list.
2850 searchURL = searchString;
2853 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2854 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2856 // Set the default `appBar` background. `this` refers to the context.
2858 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2860 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2863 // Reset `waitingForOrbot.
2864 waitingForOrbot = false;
2867 // Set swipe to refresh.
2868 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2870 // Set Do Not Track status.
2871 if (doNotTrackEnabled) {
2872 customHeaders.put("DNT", "1");
2874 customHeaders.remove("DNT");
2877 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2878 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2879 if (hideSystemBarsOnFullscreen) { // Hide everything.
2880 // Remove the translucent navigation setting if it is currently flagged.
2881 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2883 // Remove the translucent status bar overlay.
2884 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2886 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2887 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2889 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2890 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2891 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2893 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2894 } else { // Hide everything except the status and navigation bars.
2895 // Add the translucent status flag if it is unset.
2896 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2898 if (translucentNavigationBarOnFullscreen) {
2899 // Set the navigation bar to be translucent.
2900 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2902 // Set the navigation bar to be black.
2903 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2906 } else { // Switch to normal viewing mode.
2907 // Reset `inFullScreenBrowsingMode` to `false`.
2908 inFullScreenBrowsingMode = false;
2910 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2911 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2915 // Show the `BannerAd` in the free flavor.
2916 if (BuildConfig.FLAVOR.contentEquals("free")) {
2917 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2918 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2920 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2921 adView = findViewById(R.id.adview);
2924 // Remove the translucent navigation bar flag if it is set.
2925 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2927 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2928 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2930 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2931 rootCoordinatorLayout.setSystemUiVisibility(0);
2933 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2934 rootCoordinatorLayout.setFitsSystemWindows(true);
2938 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2939 @SuppressWarnings("deprecation")
2940 private void applyDomainSettings(String url) {
2941 // Reset `navigatingHistory`.
2942 navigatingHistory = false;
2944 // Parse the URL into a URI.
2945 Uri uri = Uri.parse(url);
2947 // Extract the domain from `uri`.
2948 String hostName = uri.getHost();
2950 // Initialize `loadingNewDomainName`.
2951 boolean loadingNewDomainName;
2953 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2954 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2955 //noinspection SimplifiableIfStatement
2956 if ((hostName == null) || (currentDomainName == null)) {
2957 loadingNewDomainName = true;
2958 } else { // Determine if `hostName` equals `currentDomainName`.
2959 loadingNewDomainName = !hostName.equals(currentDomainName);
2962 // 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.
2963 if (loadingNewDomainName) {
2964 // Set the new `hostname` as the `currentDomainName`.
2965 currentDomainName = hostName;
2967 // Reset `ignorePinnedSslCertificate`.
2968 ignorePinnedSslCertificate = false;
2970 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2971 favoriteIconBitmap = favoriteIconDefaultBitmap;
2972 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2974 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2975 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2976 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2978 // Get a full cursor from `domainsDatabaseHelper`.
2979 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2981 // Initialize `domainSettingsSet`.
2982 Set<String> domainSettingsSet = new HashSet<>();
2984 // Get the domain name column index.
2985 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2987 // Populate `domainSettingsSet`.
2988 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2989 // Move `domainsCursor` to the current row.
2990 domainNameCursor.moveToPosition(i);
2992 // Store the domain name in `domainSettingsSet`.
2993 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2996 // Close `domainNameCursor.
2997 domainNameCursor.close();
2999 // Initialize variables to track if domain settings will be applied and, if so, under which name.
3000 domainSettingsApplied = false;
3001 String domainNameInDatabase = null;
3003 // Check the hostname.
3004 if (domainSettingsSet.contains(hostName)) {
3005 domainSettingsApplied = true;
3006 domainNameInDatabase = hostName;
3009 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
3010 if (hostName != null) {
3011 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
3012 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
3013 domainSettingsApplied = true;
3014 domainNameInDatabase = "*." + hostName;
3017 // Strip out the lowest subdomain of `host`.
3018 hostName = hostName.substring(hostName.indexOf(".") + 1);
3022 // Get a handle for the shared preference. `this` references the current context.
3023 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
3025 // Store the general preference information.
3026 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
3027 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
3028 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
3029 nightMode = sharedPreferences.getBoolean("night_mode", false);
3031 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
3032 // Get a cursor for the current host and move it to the first position.
3033 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
3034 currentHostDomainSettingsCursor.moveToFirst();
3036 // Get the settings from the cursor.
3037 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
3038 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
3039 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
3040 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
3041 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
3042 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
3043 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
3044 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
3045 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
3046 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
3047 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
3048 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
3049 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
3050 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
3051 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
3052 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
3053 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
3055 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
3056 switch (nightModeInt) {
3057 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
3061 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
3066 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3068 javaScriptEnabled = true;
3071 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
3072 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
3073 pinnedDomainSslStartDate = null;
3075 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
3078 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
3079 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
3080 pinnedDomainSslEndDate = null;
3082 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
3085 // Close `currentHostDomainSettingsCursor`.
3086 currentHostDomainSettingsCursor.close();
3088 // Apply the domain settings.
3089 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3090 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3091 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3092 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3094 // Apply the font size.
3095 if (fontSize == 0) { // Apply the default font size.
3096 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3097 } else { // Apply the specified font size.
3098 mainWebView.getSettings().setTextZoom(fontSize);
3101 // Set third-party cookies status if API >= 21.
3102 if (Build.VERSION.SDK_INT >= 21) {
3103 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3106 // 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>
3107 if (!urlIsLoading) {
3108 switch (userAgentString) {
3109 case "System default user agent":
3110 // Set the user agent according to the system default.
3111 switch (defaultUserAgentString) {
3112 case "WebView default user agent":
3113 // Set the user agent to `""`, which uses the default value.
3114 mainWebView.getSettings().setUserAgentString("");
3117 case "Custom user agent":
3118 // Set the custom user agent.
3119 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3123 // Use the selected user agent.
3124 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3128 case "WebView default user agent":
3129 // Set the user agent to `""`, which uses the default value.
3130 mainWebView.getSettings().setUserAgentString("");
3134 // Use the selected user agent.
3135 mainWebView.getSettings().setUserAgentString(userAgentString);
3139 // 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.
3141 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
3143 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
3145 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
3146 // Store the values from `sharedPreferences` in variables.
3147 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
3148 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
3149 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
3150 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
3151 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
3153 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
3155 javaScriptEnabled = true;
3158 // Apply the default settings.
3159 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
3160 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
3161 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
3162 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
3163 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
3165 // Reset the pinned SSL certificate information.
3166 domainSettingsDatabaseId = -1;
3167 pinnedDomainSslCertificate = false;
3168 pinnedDomainSslIssuedToCNameString = "";
3169 pinnedDomainSslIssuedToONameString = "";
3170 pinnedDomainSslIssuedToUNameString = "";
3171 pinnedDomainSslIssuedByCNameString = "";
3172 pinnedDomainSslIssuedByONameString = "";
3173 pinnedDomainSslIssuedByUNameString = "";
3174 pinnedDomainSslStartDate = null;
3175 pinnedDomainSslEndDate = null;
3177 // Set third-party cookies status if API >= 21.
3178 if (Build.VERSION.SDK_INT >= 21) {
3179 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
3182 // 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>
3183 if (!urlIsLoading) {
3184 switch (defaultUserAgentString) {
3185 case "WebView default user agent":
3186 // Set the user agent to `""`, which uses the default value.
3187 mainWebView.getSettings().setUserAgentString("");
3190 case "Custom user agent":
3191 // Set the custom user agent.
3192 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
3196 // Use the selected user agent.
3197 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
3201 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
3202 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
3205 // Close `domainsDatabaseHelper`.
3206 domainsDatabaseHelper.close();
3208 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
3209 onTheFlyDisplayImagesSet = false;
3210 setDisplayWebpageImages();
3212 // Update the privacy icons, but only if `mainMenu` has already been populated.
3213 if (mainMenu != null) {
3214 updatePrivacyIcons(true);
3219 private void setDisplayWebpageImages() {
3220 if (!onTheFlyDisplayImagesSet) {
3221 if (domainSettingsApplied) { // Custom domain settings are applied.
3222 switch (displayWebpageImagesInt) {
3223 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
3224 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3227 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
3228 mainWebView.getSettings().setLoadsImagesAutomatically(true);
3231 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
3232 mainWebView.getSettings().setLoadsImagesAutomatically(false);
3235 } else { // Default settings are applied.
3236 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
3241 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
3242 // Get handles for the icons.
3243 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
3244 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
3245 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
3246 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
3248 // Update `privacyIcon`.
3249 if (javaScriptEnabled) { // JavaScript is enabled.
3250 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
3251 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
3252 privacyIconMenuItem.setIcon(R.drawable.warning);
3253 } else { // All the dangerous features are disabled.
3254 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
3257 // Update `firstPartyCookiesIcon`.
3258 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3259 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3260 } else { // First-party cookies are disabled.
3262 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3264 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3268 // Update `domStorageIcon`.
3269 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3270 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3271 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3273 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3275 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3277 } else { // JavaScript is disabled, so DOM storage is ghosted.
3279 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3281 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3285 // Update `formDataIcon`.
3286 if (saveFormDataEnabled) { // Form data is enabled.
3287 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3288 } else { // Form data is disabled.
3290 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3292 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3296 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
3297 if (runInvalidateOptionsMenu) {
3298 ActivityCompat.invalidateOptionsMenu(this);
3302 private void highlightUrlText() {
3303 String urlString = urlTextBox.getText().toString();
3305 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
3306 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3307 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
3308 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3311 // Get the index of the `/` immediately after the domain name.
3312 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3314 // De-emphasize the text after the domain name.
3315 if (endOfDomainName > 0) {
3316 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3320 private void loadBookmarksFolder() {
3321 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3322 bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3324 // Populate the bookmarks cursor adapter. `this` specifies the `Context`. `false` disables `autoRequery`.
3325 bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3327 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3328 // Inflate the individual item layout. `false` does not attach it to the root.
3329 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3333 public void bindView(View view, Context context, Cursor cursor) {
3334 // Get handles for the views.
3335 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
3336 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
3338 // Get the favorite icon byte array from the `Cursor`.
3339 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3341 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3342 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3344 // Display the bitmap in `bookmarkFavoriteIcon`.
3345 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3347 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3348 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3349 bookmarkNameTextView.setText(bookmarkNameString);
3351 // Make the font bold for folders.
3352 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3353 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3354 } else { // Reset the font to default for normal bookmarks.
3355 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3360 // Populate the `ListView` with the adapter.
3361 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3363 // Set the bookmarks drawer title.
3364 if (currentBookmarksFolder.isEmpty()) {
3365 bookmarksTitleTextView.setText(R.string.bookmarks);
3367 bookmarksTitleTextView.setText(currentBookmarksFolder);