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.RelativeLayout;
101 import android.widget.TextView;
103 import com.stoutner.privacybrowser.BannerAd;
104 import com.stoutner.privacybrowser.BuildConfig;
105 import com.stoutner.privacybrowser.R;
106 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
107 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
108 import com.stoutner.privacybrowser.dialogs.HttpAuthenticationDialog;
109 import com.stoutner.privacybrowser.dialogs.PinnedSslCertificateMismatchDialog;
110 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
111 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
112 import com.stoutner.privacybrowser.helpers.BookmarksDatabaseHelper;
113 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
114 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
115 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
116 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
118 import java.io.BufferedReader;
119 import java.io.ByteArrayInputStream;
121 import java.io.IOException;
122 import java.io.InputStreamReader;
123 import java.io.UnsupportedEncodingException;
124 import java.net.MalformedURLException;
126 import java.net.URLDecoder;
127 import java.net.URLEncoder;
128 import java.util.Date;
129 import java.util.HashMap;
130 import java.util.HashSet;
131 import java.util.Map;
132 import java.util.Set;
134 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
135 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
136 HttpAuthenticationDialog.HttpAuthenticationListener, PinnedSslCertificateMismatchDialog.PinnedSslCertificateMismatchListener, SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener,
137 DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
139 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`,
140 // `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `HttpAuthenticationDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`,
141 // `ViewSslCertificateDialog`, `CreateHomeScreenShortcutDialog`, and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
142 public static boolean darkTheme;
144 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`,
145 // and `ViewSslCertificateDialog`. It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
146 public static Bitmap favoriteIconBitmap;
148 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
149 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
150 public static String formattedUrlString;
152 // `sslCertificate` is public static so it can be accessed from `DomainsActivity`, `DomainsListFragment`, `DomainSettingsFragment`, `PinnedSslCertificateMismatchDialog`, and `ViewSslCertificateDialog`. It is also used in `onCreate()`.
153 public static SslCertificate sslCertificate;
155 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
156 public static String orbotStatus;
158 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
159 public static String webViewTitle;
161 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
162 public static boolean displayWebpageImagesBoolean;
164 // `reloadOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
165 public static boolean reloadOnRestart;
167 // `reloadUrlOnRestart` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`.
168 public static boolean loadUrlOnRestart;
170 // The pinned domain SSL Certificate variables are public static so they can be accessed from `PinnedSslCertificateMismatchDialog`. They are also used in `onCreate()` and `applyDomainSettings()`.
171 public static int domainSettingsDatabaseId;
172 public static String pinnedDomainSslIssuedToCNameString;
173 public static String pinnedDomainSslIssuedToONameString;
174 public static String pinnedDomainSslIssuedToUNameString;
175 public static String pinnedDomainSslIssuedByCNameString;
176 public static String pinnedDomainSslIssuedByONameString;
177 public static String pinnedDomainSslIssuedByUNameString;
178 public static Date pinnedDomainSslStartDate;
179 public static Date pinnedDomainSslEndDate;
182 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
183 private ActionBar appBar;
185 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchBack()`, and `applyDomainSettings()`.
186 private boolean navigatingHistory;
188 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
189 private Bitmap favoriteIconDefaultBitmap;
191 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
192 private DrawerLayout drawerLayout;
194 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
195 private CoordinatorLayout rootCoordinatorLayout;
197 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
198 // `onSslMismatchBack()`, and `setDisplayWebpageImages()`.
199 private WebView mainWebView;
201 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
202 private FrameLayout fullScreenVideoFrameLayout;
204 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
205 private SwipeRefreshLayout swipeRefreshLayout;
207 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
208 private RelativeLayout urlAppBarRelativeLayout;
210 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
211 private ImageView favoriteIconImageView;
213 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
214 private CookieManager cookieManager;
216 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
217 private final Map<String, String> customHeaders = new HashMap<>();
219 // `javaScriptEnabled` is also used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
220 private boolean javaScriptEnabled;
222 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyDomainSettings()`.
223 private boolean firstPartyCookiesEnabled;
225 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onPrepareOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
226 private boolean thirdPartyCookiesEnabled;
228 // `domStorageEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
229 private boolean domStorageEnabled;
231 // `saveFormDataEnabled` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyDomainSettings()`.
232 private boolean saveFormDataEnabled;
234 // `nightMode` is used in `onCreate()` and `applyDomainSettings()`.
235 private boolean nightMode;
237 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
238 private boolean swipeToRefreshEnabled;
240 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
241 private String homepage;
243 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
244 private String searchURL;
246 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
247 private boolean adBlockerEnabled;
249 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
250 private Runtime privacyBrowserRuntime;
252 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
253 private boolean incognitoModeEnabled;
255 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
256 private boolean fullScreenBrowsingModeEnabled;
258 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
259 private boolean inFullScreenBrowsingMode;
261 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
262 private boolean hideSystemBarsOnFullscreen;
264 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
265 private boolean translucentNavigationBarOnFullscreen;
267 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
268 private String currentDomainName;
270 // `ignorePinnedSslCertificateForDomain` is used in `onCreate()`, `onSslMismatchProceed()`, and `applyDomainSettings()`.
271 private boolean ignorePinnedSslCertificate;
273 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
274 private boolean waitingForOrbot;
276 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
277 private boolean domainSettingsApplied;
279 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
280 private int displayWebpageImagesInt;
282 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
283 private boolean onTheFlyDisplayImagesSet;
285 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
286 private String waitingForOrbotHTMLString;
288 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
289 private String privateDataDirectoryString;
291 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
292 private LinearLayout findOnPageLinearLayout;
294 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
295 private EditText findOnPageEditText;
297 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
298 private Menu mainMenu;
300 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
301 private ActionBarDrawerToggle drawerToggle;
303 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
304 private Toolbar supportAppBar;
306 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
307 private EditText urlTextBox;
309 // `redColorSpan` is used in `onCreate()` and `highlightUrlText()`.
310 private ForegroundColorSpan redColorSpan;
312 // `initialGrayColorSpan` is sued in `onCreate()` and `highlightUrlText()`.
313 private ForegroundColorSpan initialGrayColorSpan;
315 // `finalGrayColorSpam` is used in `onCreate()` and `highlightUrlText()`.
316 private ForegroundColorSpan finalGrayColorSpan;
318 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
321 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
322 private SslErrorHandler sslErrorHandler;
324 // `httpAuthHandler` is used in `onCreate()`, `onHttpAuthenticationCancel()`, and `onHttpAuthenticationProceed()`.
325 private static HttpAuthHandler httpAuthHandler;
327 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
328 private InputMethodManager inputMethodManager;
330 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
331 private RelativeLayout mainWebViewRelativeLayout;
333 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
334 private boolean urlIsLoading;
336 // `pinnedDomainSslCertificate` is used in `onCreate()` and `applyDomainSettings()`.
337 private boolean pinnedDomainSslCertificate;
339 // `bookmarksDatabaseHelper` is used in `onCreate()` and `loadBookmarksFolder()`.
340 private BookmarksDatabaseHelper bookmarksDatabaseHelper;
342 // `bookmarksListView` is used in `onCreate()` and `loadBookmarksFolder()`.
343 private ListView bookmarksListView;
345 // `currentBookmarksFolder` is used in `onCreate()`, `onBackPressed()`, and `loadBookmarksFolder()`.
346 private String currentBookmarksFolder;
348 // `bookmarksTitleTextView` is used in `onCreate()` and `loadBookmarksFolder()`.
349 private TextView bookmarksTitleTextView;
352 // 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.
353 @SuppressLint("SetJavaScriptEnabled")
354 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
355 @SuppressWarnings("deprecation")
356 protected void onCreate(Bundle savedInstanceState) {
357 // Get a handle for `sharedPreferences`. `this` references the current context.
358 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
360 // Get the theme preference.
361 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
363 // Set the activity theme.
365 setTheme(R.style.PrivacyBrowserDark);
367 setTheme(R.style.PrivacyBrowserLight);
370 // Run the default commands.
371 super.onCreate(savedInstanceState);
373 // Set the content view.
374 setContentView(R.layout.main_drawerlayout);
376 // Get a handle for `inputMethodManager`.
377 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
379 // `SupportActionBar` from `android.support.v7.app.ActionBar` must be used until the minimum API is >= 21.
380 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
381 setSupportActionBar(supportAppBar);
382 appBar = getSupportActionBar();
384 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
385 assert appBar != null;
387 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
388 appBar.setCustomView(R.layout.url_app_bar);
389 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
391 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
392 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
393 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
394 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
396 // Get a handle for `urlTextBox`.
397 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
399 // Remove the formatting from `urlTextBar` when the user is editing the text.
400 urlTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
402 public void onFocusChange(View v, boolean hasFocus) {
403 if (hasFocus) { // The user is editing `urlTextBox`.
404 // Remove the highlighting.
405 urlTextBox.getText().removeSpan(redColorSpan);
406 urlTextBox.getText().removeSpan(initialGrayColorSpan);
407 urlTextBox.getText().removeSpan(finalGrayColorSpan);
408 } else { // The user has stopped editing `urlTextBox`.
409 // Reapply the highlighting.
415 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
416 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
418 public boolean onKey(View v, int keyCode, KeyEvent event) {
419 // If the event is a key-down event on the `enter` button, load the URL.
420 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
421 // Load the URL into the mainWebView and consume the event.
423 loadUrlFromTextBox();
424 } catch (UnsupportedEncodingException e) {
427 // If the enter key was pressed, consume the event.
430 // If any other key was pressed, do not consume the event.
436 // Set `waitingForOrbotHTMLString`.
437 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
439 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
440 currentDomainName = "";
441 orbotStatus = "unknown";
442 waitingForOrbot = false;
444 // Create an Orbot status `BroadcastReceiver`.
445 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
447 public void onReceive(Context context, Intent intent) {
448 // Store the content of the status message in `orbotStatus`.
449 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
451 // If we are waiting on Orbot, load the website now that Orbot is connected.
452 if (orbotStatus.equals("ON") && waitingForOrbot) {
453 // Reset `waitingForOrbot`.
454 waitingForOrbot = false;
456 // Load `formattedUrlString
457 loadUrl(formattedUrlString);
462 // Register `orbotStatusBroadcastReceiver` on `this` context.
463 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
465 // Get handles for views that need to be accessed.
466 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
467 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
468 bookmarksListView = (ListView) findViewById(R.id.bookmarks_drawer_listview);
469 bookmarksTitleTextView = (TextView) findViewById(R.id.bookmarks_title_textview);
470 FloatingActionButton createBookmarksFolderFab = (FloatingActionButton) findViewById(R.id.create_bookmark_folder_fab);
471 FloatingActionButton createBookmarkFab = (FloatingActionButton) findViewById(R.id.create_bookmark_fab);
472 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
473 mainWebView = (WebView) findViewById(R.id.main_webview);
474 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
475 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
476 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
477 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
478 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
480 // 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.
482 createBookmarksFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_dark));
483 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_dark));
484 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.gray_850));
486 createBookmarksFolderFab.setImageDrawable(getResources().getDrawable(R.drawable.create_folder_light));
487 createBookmarkFab.setImageDrawable(getResources().getDrawable(R.drawable.create_bookmark_light));
488 bookmarksListView.setBackgroundColor(getResources().getColor(R.color.white));
491 // Create a double-tap listener to toggle full-screen mode.
492 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
493 // Override `onDoubleTap()`. All other events are handled using the default settings.
495 public boolean onDoubleTap(MotionEvent event) {
496 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
497 // Toggle `inFullScreenBrowsingMode`.
498 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
500 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
501 // Hide the `appBar`.
504 // Hide the `BannerAd` in the free flavor.
505 if (BuildConfig.FLAVOR.contentEquals("free")) {
506 BannerAd.hideAd(adView);
509 // Modify the system bars.
510 if (hideSystemBarsOnFullscreen) { // Hide everything.
511 // Remove the translucent overlays.
512 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
514 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
515 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
517 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
518 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
519 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
521 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
523 // Set `rootCoordinatorLayout` to fill the whole screen.
524 rootCoordinatorLayout.setFitsSystemWindows(false);
525 } else { // Hide everything except the status and navigation bars.
526 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
527 rootCoordinatorLayout.setFitsSystemWindows(false);
529 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.
530 // Set the navigation bar to be translucent.
531 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
534 } else { // Switch to normal viewing mode.
535 // Show the `appBar`.
538 // Show the `BannerAd` in the free flavor.
539 if (BuildConfig.FLAVOR.contentEquals("free")) {
540 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
541 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
543 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
544 adView = findViewById(R.id.adview);
547 // Remove the translucent navigation bar flag if it is set.
548 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
550 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
551 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
553 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
554 rootCoordinatorLayout.setSystemUiVisibility(0);
556 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
557 rootCoordinatorLayout.setFitsSystemWindows(true);
560 // Consume the double-tap.
562 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
568 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
569 mainWebView.setOnTouchListener(new View.OnTouchListener() {
571 public boolean onTouch(View v, MotionEvent event) {
572 // Send the `event` to `gestureDetector`.
573 return gestureDetector.onTouchEvent(event);
577 // Update `findOnPageCountTextView`.
578 mainWebView.setFindListener(new WebView.FindListener() {
579 // Get a handle for `findOnPageCountTextView`.
580 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
583 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
584 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
585 // Set `findOnPageCountTextView` to `0/0`.
586 findOnPageCountTextView.setText(R.string.zero_of_zero);
587 } else if (isDoneCounting) { // There are matches.
588 // `activeMatchOrdinal` is zero-based.
589 int activeMatch = activeMatchOrdinal + 1;
591 // Set `findOnPageCountTextView`.
592 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
597 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
598 findOnPageEditText.addTextChangedListener(new TextWatcher() {
600 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
605 public void onTextChanged(CharSequence s, int start, int before, int count) {
610 public void afterTextChanged(Editable s) {
611 // Search for the text in `mainWebView`.
612 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
616 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
617 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
619 public boolean onKey(View v, int keyCode, KeyEvent event) {
620 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
621 // Hide the soft keyboard. `0` indicates no additional flags.
622 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
624 // Consume the event.
626 } else { // A different key was pressed.
627 // Do not consume the event.
633 // Implement swipe to refresh
634 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
635 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
636 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
638 public void onRefresh() {
639 mainWebView.reload();
643 // `DrawerTitle` identifies the `DrawerLayouts` in accessibility mode.
644 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
645 drawerLayout.setDrawerTitle(GravityCompat.END, getString(R.string.bookmarks));
647 // Listen for touches on the navigation menu.
648 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
649 navigationView.setNavigationItemSelectedListener(this);
651 // 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.
652 final Menu navigationMenu = navigationView.getMenu();
653 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
654 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
655 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
657 // Initialize the bookmarks database helper. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
658 // The `0` specifies a database version, but that is ignored and set instead using a constant in `BookmarksDatabaseHelper`.
659 bookmarksDatabaseHelper = new BookmarksDatabaseHelper(this, null, null, 0);
661 // Initialize `currentBookmarksFolder`. `""` is the home folder in the database.
662 currentBookmarksFolder = "";
664 // Load the home folder, which is `""` in the database.
665 loadBookmarksFolder();
667 bookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
669 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
670 // Convert the id from long to int to match the format of the bookmarks database.
671 int databaseID = (int) id;
673 // Get the bookmark `Cursor` for this ID and move it to the first row.
674 Cursor bookmarkCursor = bookmarksDatabaseHelper.getBookmarkCursor(databaseID);
675 bookmarkCursor.moveToFirst();
677 // Act upon the bookmark according to the type.
678 if (bookmarkCursor.getInt(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) { // The selected bookmark is a folder.
679 // Store the new folder name in `currentBookmarksFolder`.
680 currentBookmarksFolder = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
682 // Load the new folder.
683 loadBookmarksFolder();
684 } else { // The selected bookmark is not a folder.
685 // Load the bookmark URL.
686 loadUrl(bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL)));
688 // Close the bookmarks drawer.
689 drawerLayout.closeDrawer(GravityCompat.END);
692 // Close the `Cursor`.
693 bookmarkCursor.close();
697 // The `DrawerListener` allows us to update the Navigation Menu.
698 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
700 public void onDrawerSlide(View drawerView, float slideOffset) {
704 public void onDrawerOpened(View drawerView) {
708 public void onDrawerClosed(View drawerView) {
712 public void onDrawerStateChanged(int newState) {
713 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
714 // Update the `Back`, `Forward`, and `History` menu items.
715 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
716 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
717 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
719 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
720 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
722 // Clear the focus from `urlTextBox` if it has it.
723 urlTextBox.clearFocus();
728 // drawerToggle creates the hamburger icon at the start of the AppBar.
729 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
731 // Initialize `adServerSet`.
732 final Set<String> adServersSet = new HashSet<>();
734 // Load the list of ad servers into memory.
736 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
737 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
739 // Create a string for storing each ad server.
742 // Populate `adServersSet`.
743 while ((adServer = bufferedReader.readLine()) != null) {
744 adServersSet.add(adServer);
747 // Close `bufferedReader`.
748 bufferedReader.close();
749 } catch (IOException ioException) {
750 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
753 mainWebView.setWebViewClient(new WebViewClient() {
754 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
755 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
756 @SuppressWarnings("deprecation")
758 public boolean shouldOverrideUrlLoading(WebView view, String url) {
759 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
760 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
761 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
763 // Parse the url and set it as the data for the `Intent`.
764 emailIntent.setData(Uri.parse(url));
766 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
767 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
770 startActivity(emailIntent);
772 // Returning `true` indicates the application is handling the URL.
774 } else { // Load the URL in Privacy Browser.
775 // Apply the domain settings for the new URL.
776 applyDomainSettings(url);
778 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
783 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
784 @SuppressWarnings("deprecation")
786 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
787 if (adBlockerEnabled) { // Block ads.
788 // Extract the host from `url`.
789 Uri requestUri = Uri.parse(url);
790 String requestHost = requestUri.getHost();
792 // Initialize a variable to track if this is an ad server.
793 boolean requestHostIsAdServer = false;
795 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
796 if (requestHost != null) {
797 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
798 if (adServersSet.contains(requestHost)) {
799 requestHostIsAdServer = true;
802 // Strip out the lowest subdomain of `requestHost`.
803 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
807 if (requestHostIsAdServer) { // It is an ad server.
808 // Return an empty `WebResourceResponse`.
809 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
810 } else { // It is not an ad server.
811 // `return null` loads the requested resource.
814 } else { // Ad blocking is disabled.
815 // `return null` loads the requested resource.
820 // Handle HTTP authentication requests.
822 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
823 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
824 httpAuthHandler = handler;
826 // Display the HTTP authentication dialog.
827 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
828 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
831 // Update the URL in urlTextBox when the page starts to load.
833 public void onPageStarted(WebView view, String url, Bitmap favicon) {
834 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
836 mainWebView.setVisibility(View.INVISIBLE);
839 // Hide the keyboard. `0` indicates no additional flags.
840 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
842 // Check to see if we are waiting on Orbot.
843 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
844 // 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.
845 formattedUrlString = url;
847 // Display the formatted URL text.
848 urlTextBox.setText(formattedUrlString);
850 // Apply text highlighting to `urlTextBox`.
853 // Apply any custom domain settings if the URL was loaded by navigating history.
854 if (navigatingHistory) {
855 applyDomainSettings(url);
858 // 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.
863 // It is necessary to update `formattedUrlString` and `urlTextBox` after the page finishes loading because the final URL can change during load.
865 public void onPageFinished(WebView view, String url) {
866 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
867 urlIsLoading = false;
869 // Clear the cache and history if Incognito Mode is enabled.
870 if (incognitoModeEnabled) {
871 // Clear the cache. `true` includes disk files.
872 mainWebView.clearCache(true);
874 // Clear the back/forward history.
875 mainWebView.clearHistory();
877 // Manually delete cache folders.
879 // Delete the main `cache` folder.
880 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
882 // 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`.
883 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
884 } catch (IOException e) {
885 // Do nothing if an error is thrown.
889 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
890 if (!waitingForOrbot) {
891 // Check to see if `WebView` has set `url` to be `about:blank`.
892 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
893 // Set `formattedUrlString` to `""`.
894 formattedUrlString = "";
896 urlTextBox.setText(formattedUrlString);
898 // Request focus for `urlTextBox`.
899 urlTextBox.requestFocus();
901 // Display the keyboard.
902 inputMethodManager.showSoftInput(urlTextBox, 0);
904 // Apply the domain settings. This clears any settings from the previous domain.
905 applyDomainSettings(formattedUrlString);
906 } else { // `WebView` has loaded a webpage.
907 // Set `formattedUrlString`.
908 formattedUrlString = url;
910 // Only update `urlTextBox` if the user is not typing in it.
911 if (!urlTextBox.hasFocus()) {
912 // Display the formatted URL text.
913 urlTextBox.setText(formattedUrlString);
915 // Apply text highlighting to `urlTextBox`.
920 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog` and `PinnedSslCertificateMismatchDialog`.
921 sslCertificate = mainWebView.getCertificate();
923 // 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.
924 if (pinnedDomainSslCertificate && !ignorePinnedSslCertificate) {
925 // Initialize the current SSL certificate variables.
926 String currentWebsiteIssuedToCName = "";
927 String currentWebsiteIssuedToOName = "";
928 String currentWebsiteIssuedToUName = "";
929 String currentWebsiteIssuedByCName = "";
930 String currentWebsiteIssuedByOName = "";
931 String currentWebsiteIssuedByUName = "";
932 Date currentWebsiteSslStartDate = null;
933 Date currentWebsiteSslEndDate = null;
936 // Extract the individual pieces of information from the current website SSL certificate if it is not null.
937 if (sslCertificate != null) {
938 currentWebsiteIssuedToCName = sslCertificate.getIssuedTo().getCName();
939 currentWebsiteIssuedToOName = sslCertificate.getIssuedTo().getOName();
940 currentWebsiteIssuedToUName = sslCertificate.getIssuedTo().getUName();
941 currentWebsiteIssuedByCName = sslCertificate.getIssuedBy().getCName();
942 currentWebsiteIssuedByOName = sslCertificate.getIssuedBy().getOName();
943 currentWebsiteIssuedByUName = sslCertificate.getIssuedBy().getUName();
944 currentWebsiteSslStartDate = sslCertificate.getValidNotBeforeDate();
945 currentWebsiteSslEndDate = sslCertificate.getValidNotAfterDate();
948 // 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`.
949 String currentWebsiteSslStartDateString = "";
950 String currentWebsiteSslEndDateString = "";
951 String pinnedDomainSslStartDateString = "";
952 String pinnedDomainSslEndDateString = "";
954 // Convert the `Dates` to `Strings` if they are not `null`.
955 if (currentWebsiteSslStartDate != null) {
956 currentWebsiteSslStartDateString = currentWebsiteSslStartDate.toString();
959 if (currentWebsiteSslEndDate != null) {
960 currentWebsiteSslEndDateString = currentWebsiteSslEndDate.toString();
963 if (pinnedDomainSslStartDate != null) {
964 pinnedDomainSslStartDateString = pinnedDomainSslStartDate.toString();
967 if (pinnedDomainSslEndDate != null) {
968 pinnedDomainSslEndDateString = pinnedDomainSslEndDate.toString();
971 // Check to see if the pinned SSL certificate matches the current website certificate.
972 if (!currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) || !currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) || !currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) ||
973 !currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) || !currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) || !currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) ||
974 !currentWebsiteSslStartDateString.equals(pinnedDomainSslStartDateString) || !currentWebsiteSslEndDateString.equals(pinnedDomainSslEndDateString)) { // The pinned SSL certificate doesn't match the current domain certificate.
975 //Display the pinned SSL certificate mismatch `AlertDialog`.
976 AppCompatDialogFragment pinnedSslCertificateMismatchDialogFragment = new PinnedSslCertificateMismatchDialog();
977 pinnedSslCertificateMismatchDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_mismatch));
983 // Handle SSL Certificate errors.
985 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
986 // Get the current website SSL certificate.
987 SslCertificate currentWebsiteSslCertificate = error.getCertificate();
989 // Extract the individual pieces of information from the current website SSL certificate.
990 String currentWebsiteIssuedToCName = currentWebsiteSslCertificate.getIssuedTo().getCName();
991 String currentWebsiteIssuedToOName = currentWebsiteSslCertificate.getIssuedTo().getOName();
992 String currentWebsiteIssuedToUName = currentWebsiteSslCertificate.getIssuedTo().getUName();
993 String currentWebsiteIssuedByCName = currentWebsiteSslCertificate.getIssuedBy().getCName();
994 String currentWebsiteIssuedByOName = currentWebsiteSslCertificate.getIssuedBy().getOName();
995 String currentWebsiteIssuedByUName = currentWebsiteSslCertificate.getIssuedBy().getUName();
996 Date currentWebsiteSslStartDate = currentWebsiteSslCertificate.getValidNotBeforeDate();
997 Date currentWebsiteSslEndDate = currentWebsiteSslCertificate.getValidNotAfterDate();
999 // Proceed to the website if the current SSL website certificate matches the pinned domain certificate.
1000 if (pinnedDomainSslCertificate &&
1001 currentWebsiteIssuedToCName.equals(pinnedDomainSslIssuedToCNameString) && currentWebsiteIssuedToOName.equals(pinnedDomainSslIssuedToONameString) && currentWebsiteIssuedToUName.equals(pinnedDomainSslIssuedToUNameString) &&
1002 currentWebsiteIssuedByCName.equals(pinnedDomainSslIssuedByCNameString) && currentWebsiteIssuedByOName.equals(pinnedDomainSslIssuedByONameString) && currentWebsiteIssuedByUName.equals(pinnedDomainSslIssuedByUNameString) &&
1003 currentWebsiteSslStartDate.equals(pinnedDomainSslStartDate) && currentWebsiteSslEndDate.equals(pinnedDomainSslEndDate)) { // An SSL certificate is pinned and matches the current domain certificate.
1004 // Proceed to the website without displaying an error.
1006 } else { // Either there isn't a pinned SSL certificate or it doesn't match the current website certificate.
1007 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
1008 sslErrorHandler = handler;
1010 // Display the SSL error `AlertDialog`.
1011 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
1012 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getString(R.string.ssl_certificate_error));
1017 // Get a handle for the progress bar.
1018 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
1020 mainWebView.setWebChromeClient(new WebChromeClient() {
1021 // Update the progress bar when a page is loading.
1023 public void onProgressChanged(WebView view, int progress) {
1024 // Inject the night mode CSS if night mode is enabled.
1026 // `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.
1027 // `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.
1028 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
1029 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '" +
1030 "* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important; text-shadow: none !important; border: none !important;}" +
1031 "a {color: #1565C0 !important;}" +
1032 "'; parent.appendChild(style)})()", new ValueCallback<String>() {
1034 public void onReceiveValue(String value) {
1035 // Initialize a `Handler` to display `mainWebView`.
1036 Handler displayWebViewHandler = new Handler();
1038 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
1039 Runnable displayWebViewRunnable = new Runnable() {
1041 // Only display `mainWebView` if the progress bar is one. This prevents the display of the `WebView` while it is still loading.
1042 if (progressBar.getVisibility() == View.GONE) {
1043 mainWebView.setVisibility(View.VISIBLE);
1048 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
1049 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
1054 progressBar.setProgress(progress);
1055 if (progress < 100) {
1056 // Show the progress bar.
1057 progressBar.setVisibility(View.VISIBLE);
1059 // Hide the progress bar.
1060 progressBar.setVisibility(View.GONE);
1062 // Display `mainWebView` if night mode is disabled.
1063 // 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.
1065 mainWebView.setVisibility(View.VISIBLE);
1068 //Stop the `SwipeToRefresh` indicator if it is running
1069 swipeRefreshLayout.setRefreshing(false);
1073 // Set the favorite icon when it changes.
1075 public void onReceivedIcon(WebView view, Bitmap icon) {
1076 // Only update the favorite icon if the website has finished loading.
1077 if (progressBar.getVisibility() == View.GONE) {
1078 // Save a copy of the favorite icon.
1079 favoriteIconBitmap = icon;
1081 // Place the favorite icon in the appBar.
1082 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1086 // Save a copy of the title when it changes.
1088 public void onReceivedTitle(WebView view, String title) {
1089 // Save a copy of the title.
1090 webViewTitle = title;
1093 // Enter full screen video
1095 public void onShowCustomView(View view, CustomViewCallback callback) {
1096 // Pause the ad if this is the free flavor.
1097 if (BuildConfig.FLAVOR.contentEquals("free")) {
1098 BannerAd.pauseAd(adView);
1101 // Remove the translucent overlays.
1102 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1104 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1105 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1107 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1108 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1109 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1111 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1113 // Set `rootCoordinatorLayout` to fill the entire screen.
1114 rootCoordinatorLayout.setFitsSystemWindows(false);
1116 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1117 fullScreenVideoFrameLayout.addView(view);
1118 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1121 // Exit full screen video
1122 public void onHideCustomView() {
1123 // Hide `fullScreenVideoFrameLayout`.
1124 fullScreenVideoFrameLayout.removeAllViews();
1125 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1127 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1128 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1130 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1131 rootCoordinatorLayout.setFitsSystemWindows(true);
1133 // Show the ad if this is the free flavor.
1134 if (BuildConfig.FLAVOR.contentEquals("free")) {
1135 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1136 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1138 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1139 adView = findViewById(R.id.adview);
1144 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1145 registerForContextMenu(mainWebView);
1147 // Allow the downloading of files.
1148 mainWebView.setDownloadListener(new DownloadListener() {
1150 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
1151 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1152 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1153 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1157 // Allow pinch to zoom.
1158 mainWebView.getSettings().setBuiltInZoomControls(true);
1160 // Hide zoom controls.
1161 mainWebView.getSettings().setDisplayZoomControls(false);
1163 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1164 mainWebView.getSettings().setUseWideViewPort(true);
1166 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1167 mainWebView.getSettings().setLoadWithOverviewMode(true);
1169 // Explicitly disable geolocation.
1170 mainWebView.getSettings().setGeolocationEnabled(false);
1172 // Initialize cookieManager.
1173 cookieManager = CookieManager.getInstance();
1175 // 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).
1176 customHeaders.put("X-Requested-With", "");
1178 // 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.
1179 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1181 // Get the intent that started the app.
1182 final Intent launchingIntent = getIntent();
1184 // Extract the launching intent data as `launchingIntentUriData`.
1185 final Uri launchingIntentUriData = launchingIntent.getData();
1187 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1188 if (launchingIntentUriData != null) {
1189 formattedUrlString = launchingIntentUriData.toString();
1192 // Get a handle for the `Runtime`.
1193 privacyBrowserRuntime = Runtime.getRuntime();
1195 // Store the application's private data directory.
1196 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`.
1198 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1199 inFullScreenBrowsingMode = false;
1201 // Initialize AdView for the free flavor.
1202 adView = findViewById(R.id.adview);
1204 // Initialize the privacy settings variables.
1205 javaScriptEnabled = false;
1206 firstPartyCookiesEnabled = false;
1207 thirdPartyCookiesEnabled = false;
1208 domStorageEnabled = false;
1209 saveFormDataEnabled = false;
1212 // Initialize `webViewTitle`.
1213 webViewTitle = getString(R.string.no_title);
1215 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1216 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1217 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1218 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1220 // If the favorite icon is null, load the default.
1221 if (favoriteIconBitmap == null) {
1222 favoriteIconBitmap = favoriteIconDefaultBitmap;
1225 // Apply the app settings from the shared preferences.
1228 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1229 if (!waitingForOrbot) {
1230 loadUrl(formattedUrlString);
1235 protected void onNewIntent(Intent intent) {
1236 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1239 if (intent.getData() != null) {
1240 // Get the intent data and convert it to a string.
1241 final Uri intentUriData = intent.getData();
1242 formattedUrlString = intentUriData.toString();
1245 // Close the navigation drawer if it is open.
1246 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1247 drawerLayout.closeDrawer(GravityCompat.START);
1250 // Load the website.
1251 loadUrl(formattedUrlString);
1253 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1254 mainWebView.requestFocus();
1258 public void onRestart() {
1261 // Apply the app settings, which may have been changed in `SettingsActivity`.
1264 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1265 updatePrivacyIcons(true);
1267 // Set the display webpage images mode.
1268 setDisplayWebpageImages();
1270 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1271 if (reloadOnRestart) {
1272 // Reload `mainWebView`.
1273 mainWebView.reload();
1275 // Reset `reloadOnRestartBoolean`.
1276 reloadOnRestart = false;
1279 // Load the URL on restart to apply changes to night mode.
1280 if (loadUrlOnRestart) {
1281 // Load the current `formattedUrlString`.
1282 loadUrl(formattedUrlString);
1284 // Reset `loadUrlOnRestart.
1285 loadUrlOnRestart = false;
1289 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1291 public void onResume() {
1294 // Resume JavaScript (if enabled).
1295 mainWebView.resumeTimers();
1297 // Resume `mainWebView`.
1298 mainWebView.onResume();
1300 // Resume the adView for the free flavor.
1301 if (BuildConfig.FLAVOR.contentEquals("free")) {
1302 BannerAd.resumeAd(adView);
1307 public void onPause() {
1308 // Pause `mainWebView`.
1309 mainWebView.onPause();
1311 // Stop all JavaScript.
1312 mainWebView.pauseTimers();
1314 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1315 if (BuildConfig.FLAVOR.contentEquals("free")) {
1316 BannerAd.pauseAd(adView);
1323 public boolean onCreateOptionsMenu(Menu menu) {
1324 // Inflate the menu; this adds items to the action bar if it is present.
1325 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1327 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1330 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1331 updatePrivacyIcons(false);
1333 // Get handles for the menu items.
1334 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1335 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1336 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1337 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1339 // Only display third-party cookies if SDK >= 21
1340 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1342 // Get the shared preference values. `this` references the current context.
1343 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1345 // Set the status of the additional app bar icons. The default is `false`.
1346 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1347 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1348 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1349 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1350 } else { //Do not display the additional icons.
1351 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1352 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1353 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1360 public boolean onPrepareOptionsMenu(Menu menu) {
1361 // Get handles for the menu items.
1362 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1363 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1364 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1365 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1366 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1367 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1368 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1369 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1370 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1371 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1373 // Set the status of the menu item checkboxes.
1374 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1375 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1376 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1377 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1378 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1380 // Enable third-party cookies if first-party cookies are enabled.
1381 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1383 // Enable `DOM Storage` if JavaScript is enabled.
1384 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1386 // Enable `Clear Cookies` if there are any.
1387 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1389 // Get a count of the number of files in the `Local Storage` directory.
1390 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1391 int localStorageDirectoryNumberOfFiles = 0;
1392 if (localStorageDirectory.exists()) {
1393 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1396 // Get a count of the number of files in the `IndexedDB` directory.
1397 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1398 int indexedDBDirectoryNumberOfFiles = 0;
1399 if (indexedDBDirectory.exists()) {
1400 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1403 // Enable `Clear DOM Storage` if there is any.
1404 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1406 // Enable `Clear Form Data` is there is any.
1407 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1408 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1410 // Initialize font size variables.
1411 int fontSize = mainWebView.getSettings().getTextZoom();
1412 String fontSizeTitle;
1413 MenuItem selectedFontSizeMenuItem;
1415 // Prepare the font size title and current size menu item.
1418 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1419 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1423 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1424 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1428 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1429 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1433 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1434 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1438 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1439 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1443 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1444 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1448 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1449 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1453 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1454 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1458 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1459 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1463 // Set the font size title and select the current size menu item.
1464 fontSizeMenuItem.setTitle(fontSizeTitle);
1465 selectedFontSizeMenuItem.setChecked(true);
1467 // Only show `Refresh` if `swipeToRefresh` is disabled.
1468 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1470 // Run all the other default commands.
1471 super.onPrepareOptionsMenu(menu);
1473 // `return true` displays the menu.
1478 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1479 @SuppressLint("SetJavaScriptEnabled")
1480 // removeAllCookies is deprecated, but it is required for API < 21.
1481 @SuppressWarnings("deprecation")
1482 public boolean onOptionsItemSelected(MenuItem menuItem) {
1483 int menuItemId = menuItem.getItemId();
1485 // Set the commands that relate to the menu entries.
1486 switch (menuItemId) {
1487 case R.id.toggle_javascript:
1488 // Switch the status of javaScriptEnabled.
1489 javaScriptEnabled = !javaScriptEnabled;
1491 // Apply the new JavaScript status.
1492 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1494 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1495 updatePrivacyIcons(true);
1497 // Display a `Snackbar`.
1498 if (javaScriptEnabled) { // JavaScrip is enabled.
1499 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1500 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1501 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1502 } else { // Privacy mode.
1503 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1506 // Reload the WebView.
1507 mainWebView.reload();
1510 case R.id.toggle_first_party_cookies:
1511 // Switch the status of firstPartyCookiesEnabled.
1512 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1514 // Update the menu checkbox.
1515 menuItem.setChecked(firstPartyCookiesEnabled);
1517 // Apply the new cookie status.
1518 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1520 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1521 updatePrivacyIcons(true);
1523 // Display a `Snackbar`.
1524 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1525 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1526 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1527 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1528 } else { // Privacy mode.
1529 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1532 // Reload the WebView.
1533 mainWebView.reload();
1536 case R.id.toggle_third_party_cookies:
1537 if (Build.VERSION.SDK_INT >= 21) {
1538 // Switch the status of thirdPartyCookiesEnabled.
1539 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1541 // Update the menu checkbox.
1542 menuItem.setChecked(thirdPartyCookiesEnabled);
1544 // Apply the new cookie status.
1545 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1547 // Display a `Snackbar`.
1548 if (thirdPartyCookiesEnabled) {
1549 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1551 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1554 // Reload the WebView.
1555 mainWebView.reload();
1556 } // Else do nothing because SDK < 21.
1559 case R.id.toggle_dom_storage:
1560 // Switch the status of domStorageEnabled.
1561 domStorageEnabled = !domStorageEnabled;
1563 // Update the menu checkbox.
1564 menuItem.setChecked(domStorageEnabled);
1566 // Apply the new DOM Storage status.
1567 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1569 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1570 updatePrivacyIcons(true);
1572 // Display a `Snackbar`.
1573 if (domStorageEnabled) {
1574 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1576 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1579 // Reload the WebView.
1580 mainWebView.reload();
1583 case R.id.toggle_save_form_data:
1584 // Switch the status of saveFormDataEnabled.
1585 saveFormDataEnabled = !saveFormDataEnabled;
1587 // Update the menu checkbox.
1588 menuItem.setChecked(saveFormDataEnabled);
1590 // Apply the new form data status.
1591 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1593 // Display a `Snackbar`.
1594 if (saveFormDataEnabled) {
1595 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1597 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1600 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1601 updatePrivacyIcons(true);
1603 // Reload the WebView.
1604 mainWebView.reload();
1607 case R.id.clear_cookies:
1608 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1609 .setAction(R.string.undo, new View.OnClickListener() {
1611 public void onClick(View v) {
1612 // Do nothing because everything will be handled by `onDismissed()` below.
1615 .addCallback(new Snackbar.Callback() {
1617 public void onDismissed(Snackbar snackbar, int event) {
1619 // The user pushed the `Undo` button.
1620 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1624 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1626 // `cookieManager.removeAllCookie()` varies by SDK.
1627 if (Build.VERSION.SDK_INT < 21) {
1628 cookieManager.removeAllCookie();
1630 // `null` indicates no callback.
1631 cookieManager.removeAllCookies(null);
1639 case R.id.clear_dom_storage:
1640 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1641 .setAction(R.string.undo, new View.OnClickListener() {
1643 public void onClick(View v) {
1644 // Do nothing because everything will be handled by `onDismissed()` below.
1647 .addCallback(new Snackbar.Callback() {
1649 public void onDismissed(Snackbar snackbar, int event) {
1651 // The user pushed the `Undo` button.
1652 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1656 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1658 // Delete the DOM Storage.
1659 WebStorage webStorage = WebStorage.getInstance();
1660 webStorage.deleteAllData();
1662 // Manually remove `IndexedDB` if it exists.
1664 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1665 } catch (IOException e) {
1666 // Do nothing if an error is thrown.
1674 case R.id.clear_form_data:
1675 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1676 .setAction(R.string.undo, new View.OnClickListener() {
1678 public void onClick(View v) {
1679 // Do nothing because everything will be handled by `onDismissed()` below.
1682 .addCallback(new Snackbar.Callback() {
1684 public void onDismissed(Snackbar snackbar, int event) {
1686 // The user pushed the `Undo` button.
1687 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1691 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1693 // Delete the form data.
1694 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1695 mainWebViewDatabase.clearFormData();
1702 case R.id.font_size_twenty_five_percent:
1703 mainWebView.getSettings().setTextZoom(25);
1706 case R.id.font_size_fifty_percent:
1707 mainWebView.getSettings().setTextZoom(50);
1710 case R.id.font_size_seventy_five_percent:
1711 mainWebView.getSettings().setTextZoom(75);
1714 case R.id.font_size_one_hundred_percent:
1715 mainWebView.getSettings().setTextZoom(100);
1718 case R.id.font_size_one_hundred_twenty_five_percent:
1719 mainWebView.getSettings().setTextZoom(125);
1722 case R.id.font_size_one_hundred_fifty_percent:
1723 mainWebView.getSettings().setTextZoom(150);
1726 case R.id.font_size_one_hundred_seventy_five_percent:
1727 mainWebView.getSettings().setTextZoom(175);
1730 case R.id.font_size_two_hundred_percent:
1731 mainWebView.getSettings().setTextZoom(200);
1734 case R.id.display_images:
1735 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1736 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1737 mainWebView.reload();
1738 } else { // Images are not currently loaded automatically.
1739 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1742 // Set `onTheFlyDisplayImagesSet`.
1743 onTheFlyDisplayImagesSet = true;
1747 // Setup the share string.
1748 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1750 // Create the share intent.
1751 Intent shareIntent = new Intent();
1752 shareIntent.setAction(Intent.ACTION_SEND);
1753 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1754 shareIntent.setType("text/plain");
1757 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1760 case R.id.find_on_page:
1761 // Hide the URL app bar.
1762 supportAppBar.setVisibility(View.GONE);
1764 // Show the Find on Page `RelativeLayout`.
1765 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1767 // 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
1768 findOnPageEditText.postDelayed(new Runnable() {
1772 // Set the focus on `findOnPageEditText`.
1773 findOnPageEditText.requestFocus();
1775 // Display the keyboard. `0` sets no input flags.
1776 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1782 // Get a `PrintManager` instance.
1783 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1785 // Convert `mainWebView` to `printDocumentAdapter`.
1786 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1788 // Print the document. The print attributes are `null`.
1789 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1792 case R.id.add_to_homescreen:
1793 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1794 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1795 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1797 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1801 mainWebView.reload();
1805 // Don't consume the event.
1806 return super.onOptionsItemSelected(menuItem);
1810 // removeAllCookies is deprecated, but it is required for API < 21.
1811 @SuppressWarnings("deprecation")
1813 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1814 int menuItemId = menuItem.getItemId();
1816 switch (menuItemId) {
1822 if (mainWebView.canGoBack()) {
1823 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1824 navigatingHistory = true;
1826 // Load the previous website in the history.
1827 mainWebView.goBack();
1832 if (mainWebView.canGoForward()) {
1833 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1834 navigatingHistory = true;
1836 // Load the next website in the history.
1837 mainWebView.goForward();
1842 // Get the `WebBackForwardList`.
1843 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1845 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1846 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1847 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1850 case R.id.bookmarks:
1851 // Launch BookmarksActivity.
1852 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1853 startActivity(bookmarksIntent);
1856 case R.id.downloads:
1857 // Launch the system Download Manager.
1858 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1860 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1861 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1863 startActivity(downloadManagerIntent);
1867 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1868 currentDomainName = "";
1870 // Launch `SettingsActivity`.
1871 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1872 startActivity(settingsIntent);
1876 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1877 currentDomainName = "";
1879 // Launch `DomainsActivity`.
1880 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1881 startActivity(domainsIntent);
1885 // Launch `GuideActivity`.
1886 Intent guideIntent = new Intent(this, GuideActivity.class);
1887 startActivity(guideIntent);
1891 // Launch `AboutActivity`.
1892 Intent aboutIntent = new Intent(this, AboutActivity.class);
1893 startActivity(aboutIntent);
1896 case R.id.clearAndExit:
1897 // Get a handle for `sharedPreferences`. `this` references the current context.
1898 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1900 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1903 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1904 // The command to remove cookies changed slightly in API 21.
1905 if (Build.VERSION.SDK_INT >= 21) {
1906 cookieManager.removeAllCookies(null);
1908 cookieManager.removeAllCookie();
1911 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1913 // We have to use two commands because `Runtime.exec()` does not like `*`.
1914 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1915 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1916 } catch (IOException e) {
1917 // Do nothing if an error is thrown.
1921 // Clear DOM storage.
1922 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1923 // Ask `WebStorage` to clear the DOM storage.
1924 WebStorage webStorage = WebStorage.getInstance();
1925 webStorage.deleteAllData();
1927 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1929 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1930 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1932 // We have to use multiple commands because `Runtime.exec()` does not like `*`.
1933 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1934 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1935 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1936 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1937 } catch (IOException e) {
1938 // Do nothing if an error is thrown.
1943 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1944 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1945 webViewDatabase.clearFormData();
1947 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1949 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1950 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1951 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1952 } catch (IOException e) {
1953 // Do nothing if an error is thrown.
1958 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1959 // `true` includes disk files.
1960 mainWebView.clearCache(true);
1962 // Manually delete the cache directories.
1964 // Delete the main cache directory.
1965 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1967 // 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.
1968 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1969 } catch (IOException e) {
1970 // Do nothing if an error is thrown.
1974 // Clear SSL certificate preferences.
1975 mainWebView.clearSslPreferences();
1977 // Clear the back/forward history.
1978 mainWebView.clearHistory();
1980 // Clear `formattedUrlString`.
1981 formattedUrlString = null;
1983 // Clear `customHeaders`.
1984 customHeaders.clear();
1986 // Detach all views from `mainWebViewRelativeLayout`.
1987 mainWebViewRelativeLayout.removeAllViews();
1989 // Destroy the internal state of `mainWebView`.
1990 mainWebView.destroy();
1992 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1993 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1994 if (clearEverything) {
1996 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1997 } catch (IOException e) {
1998 // Do nothing if an error is thrown.
2002 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
2003 if (Build.VERSION.SDK_INT >= 21) {
2004 finishAndRemoveTask();
2009 // Remove the terminated program from RAM. The status code is `0`.
2014 // Close the navigation drawer.
2015 drawerLayout.closeDrawer(GravityCompat.START);
2020 public void onPostCreate(Bundle savedInstanceState) {
2021 super.onPostCreate(savedInstanceState);
2023 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2024 drawerToggle.syncState();
2028 public void onConfigurationChanged(Configuration newConfig) {
2029 super.onConfigurationChanged(newConfig);
2031 // Reload the ad for the free flavor if we are not in full screen mode.
2032 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2034 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2036 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2037 adView = findViewById(R.id.adview);
2040 // `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
2041 // ActivityCompat.invalidateOptionsMenu(this);
2045 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2046 // Store the `HitTestResult`.
2047 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2050 final String imageUrl;
2051 final String linkUrl;
2053 // Get a handle for the `ClipboardManager`.
2054 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2056 switch (hitTestResult.getType()) {
2057 // `SRC_ANCHOR_TYPE` is a link.
2058 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2059 // Get the target URL.
2060 linkUrl = hitTestResult.getExtra();
2062 // Set the target URL as the title of the `ContextMenu`.
2063 menu.setHeaderTitle(linkUrl);
2065 // Add a `Load URL` entry.
2066 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2068 public boolean onMenuItemClick(MenuItem item) {
2074 // Add a `Copy URL` entry.
2075 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2077 public boolean onMenuItemClick(MenuItem item) {
2078 // Save the link URL in a `ClipData`.
2079 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2081 // Set the `ClipData` as the clipboard's primary clip.
2082 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2087 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2088 menu.add(R.string.cancel);
2091 case WebView.HitTestResult.EMAIL_TYPE:
2092 // Get the target URL.
2093 linkUrl = hitTestResult.getExtra();
2095 // Set the target URL as the title of the `ContextMenu`.
2096 menu.setHeaderTitle(linkUrl);
2098 // Add a `Write Email` entry.
2099 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2101 public boolean onMenuItemClick(MenuItem item) {
2102 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2103 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2105 // Parse the url and set it as the data for the `Intent`.
2106 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2108 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2109 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2112 startActivity(emailIntent);
2117 // Add a `Copy Email Address` entry.
2118 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2120 public boolean onMenuItemClick(MenuItem item) {
2121 // Save the email address in a `ClipData`.
2122 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2124 // Set the `ClipData` as the clipboard's primary clip.
2125 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2130 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2131 menu.add(R.string.cancel);
2134 // `IMAGE_TYPE` is an image.
2135 case WebView.HitTestResult.IMAGE_TYPE:
2136 // Get the image URL.
2137 imageUrl = hitTestResult.getExtra();
2139 // Set the image URL as the title of the `ContextMenu`.
2140 menu.setHeaderTitle(imageUrl);
2142 // Add a `View Image` entry.
2143 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2145 public boolean onMenuItemClick(MenuItem item) {
2151 // Add a `Download Image` entry.
2152 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2154 public boolean onMenuItemClick(MenuItem item) {
2155 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2156 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2157 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2162 // Add a `Copy URL` entry.
2163 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2165 public boolean onMenuItemClick(MenuItem item) {
2166 // Save the image URL in a `ClipData`.
2167 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2169 // Set the `ClipData` as the clipboard's primary clip.
2170 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2175 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2176 menu.add(R.string.cancel);
2180 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2181 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2182 // Get the image URL.
2183 imageUrl = hitTestResult.getExtra();
2185 // Set the image URL as the title of the `ContextMenu`.
2186 menu.setHeaderTitle(imageUrl);
2188 // Add a `View Image` entry.
2189 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2191 public boolean onMenuItemClick(MenuItem item) {
2197 // Add a `Download Image` entry.
2198 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2200 public boolean onMenuItemClick(MenuItem item) {
2201 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2202 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2203 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2208 // Add a `Copy URL` entry.
2209 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2211 public boolean onMenuItemClick(MenuItem item) {
2212 // Save the image URL in a `ClipData`.
2213 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2215 // Set the `ClipData` as the clipboard's primary clip.
2216 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2221 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2222 menu.add(R.string.cancel);
2228 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2229 // Get shortcutNameEditText from the alert dialog.
2230 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2232 // Create the bookmark shortcut based on formattedUrlString.
2233 Intent bookmarkShortcut = new Intent();
2234 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
2235 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
2237 // Place the bookmark shortcut on the home screen.
2238 Intent placeBookmarkShortcut = new Intent();
2239 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
2240 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
2241 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
2242 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
2243 sendBroadcast(placeBookmarkShortcut);
2247 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2248 // Download the image if it has an HTTP or HTTPS URI.
2249 if (imageUrl.startsWith("http")) {
2250 // Get a handle for the system `DOWNLOAD_SERVICE`.
2251 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2253 // Parse `imageUrl`.
2254 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2256 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2257 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2258 if (firstPartyCookiesEnabled) {
2259 // Get the cookies for `imageUrl`.
2260 String cookies = cookieManager.getCookie(imageUrl);
2262 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2263 downloadRequest.addRequestHeader("Cookie", cookies);
2266 // Get the file name from `dialogFragment`.
2267 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
2268 String imageName = downloadImageNameEditText.getText().toString();
2270 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2271 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2272 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2273 } else { // Only set the title using `imageName`.
2274 downloadRequest.setTitle(imageName);
2277 // Allow `MediaScanner` to index the download if it is a media file.
2278 downloadRequest.allowScanningByMediaScanner();
2280 // Add the URL as the description for the download.
2281 downloadRequest.setDescription(imageUrl);
2283 // Show the download notification after the download is completed.
2284 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2286 // Initiate the download.
2287 downloadManager.enqueue(downloadRequest);
2288 } else { // The image is not an HTTP or HTTPS URI.
2289 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2294 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2295 // Download the file if it has an HTTP or HTTPS URI.
2296 if (downloadUrl.startsWith("http")) {
2298 // Get a handle for the system `DOWNLOAD_SERVICE`.
2299 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2301 // Parse `downloadUrl`.
2302 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2304 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2305 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2306 if (firstPartyCookiesEnabled) {
2307 // Get the cookies for `downloadUrl`.
2308 String cookies = cookieManager.getCookie(downloadUrl);
2310 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2311 downloadRequest.addRequestHeader("Cookie", cookies);
2314 // Get the file name from `dialogFragment`.
2315 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2316 String fileName = downloadFileNameEditText.getText().toString();
2318 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2319 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2320 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2321 } else { // Only set the title using `fileName`.
2322 downloadRequest.setTitle(fileName);
2325 // Allow `MediaScanner` to index the download if it is a media file.
2326 downloadRequest.allowScanningByMediaScanner();
2328 // Add the URL as the description for the download.
2329 downloadRequest.setDescription(downloadUrl);
2331 // Show the download notification after the download is completed.
2332 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2334 // Initiate the download.
2335 downloadManager.enqueue(downloadRequest);
2336 } else { // The download is not an HTTP or HTTPS URI.
2337 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2342 public void onHttpAuthenticationCancel() {
2343 // Cancel the `HttpAuthHandler`.
2344 httpAuthHandler.cancel();
2348 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2349 // Get handles for the `EditTexts`.
2350 EditText usernameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2351 EditText passwordEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2353 // Proceed with the HTTP authentication.
2354 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2357 public void viewSslCertificate(View view) {
2358 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2359 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2360 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2364 public void onSslErrorCancel() {
2365 sslErrorHandler.cancel();
2369 public void onSslErrorProceed() {
2370 sslErrorHandler.proceed();
2374 public void onSslMismatchBack() {
2375 if (mainWebView.canGoBack()) { // There is a back page in the history.
2376 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2377 navigatingHistory = true;
2380 mainWebView.goBack();
2381 } else { // There are no pages to go back to.
2382 // Load a blank page
2388 public void onSslMismatchProceed() {
2389 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2390 ignorePinnedSslCertificate = true;
2394 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2395 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2396 navigatingHistory = true;
2398 // Load the history entry.
2399 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2403 public void onClearHistory() {
2404 // Clear the history.
2405 mainWebView.clearHistory();
2408 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2410 public void onBackPressed() {
2411 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2412 // Close the navigation drawer.
2413 drawerLayout.closeDrawer(GravityCompat.START);
2414 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2415 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2416 // close the bookmarks drawer.
2417 drawerLayout.closeDrawer(GravityCompat.END);
2418 } else { // A subfolder is displayed.
2419 // Place the former parent folder in `currentFolder`.
2420 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2422 // Load the new folder.
2423 loadBookmarksFolder();
2426 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2427 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2428 navigatingHistory = true;
2431 mainWebView.goBack();
2432 } else { // There isn't anything to do in Privacy Browser.
2433 // Pass `onBackPressed()` to the system.
2434 super.onBackPressed();
2438 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2439 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2440 String unformattedUrlString = urlTextBox.getText().toString().trim();
2442 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2443 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2444 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2445 if (!unformattedUrlString.startsWith("http")) {
2446 unformattedUrlString = "http://" + unformattedUrlString;
2449 // Initialize `unformattedUrl`.
2450 URL unformattedUrl = null;
2452 // 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.
2454 unformattedUrl = new URL(unformattedUrlString);
2455 } catch (MalformedURLException e) {
2456 e.printStackTrace();
2459 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2460 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2461 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2462 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2463 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2464 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2467 Uri.Builder formattedUri = new Uri.Builder();
2468 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2470 // Decode `formattedUri` as a `String` in `UTF-8`.
2471 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2473 // Sanitize the search input and convert it to a search.
2474 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2476 // Add the base search URL.
2477 formattedUrlString = searchURL + encodedUrlString;
2480 loadUrl(formattedUrlString);
2484 private void loadUrl(String url) {
2485 // Apply any custom domain settings.
2486 applyDomainSettings(url);
2489 mainWebView.loadUrl(url, customHeaders);
2491 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2492 urlIsLoading = true;
2495 public void findPreviousOnPage(View view) {
2496 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2497 mainWebView.findNext(false);
2500 public void findNextOnPage(View view) {
2501 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2502 mainWebView.findNext(true);
2505 public void closeFindOnPage(View view) {
2506 // Delete the contents of `find_on_page_edittext`.
2507 findOnPageEditText.setText(null);
2509 // Clear the highlighted phrases.
2510 mainWebView.clearMatches();
2512 // Hide the Find on Page `RelativeLayout`.
2513 findOnPageLinearLayout.setVisibility(View.GONE);
2515 // Show the URL app bar.
2516 supportAppBar.setVisibility(View.VISIBLE);
2518 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2519 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2522 private void applyAppSettings() {
2523 // Get a handle for `sharedPreferences`. `this` references the current context.
2524 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2526 // Store the values from `sharedPreferences` in variables.
2527 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2528 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2529 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2530 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2531 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2532 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2533 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2534 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2535 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2536 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2537 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2538 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2539 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2540 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2541 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2543 // Set the homepage, search, and proxy options.
2544 if (proxyThroughOrbot) { // Set the Tor options.
2545 // Set `torHomepageString` as `homepage`.
2546 homepage = torHomepageString;
2548 // If formattedUrlString is null assign the homepage to it.
2549 if (formattedUrlString == null) {
2550 formattedUrlString = homepage;
2553 // Set the search URL.
2554 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2555 searchURL = torSearchCustomURLString;
2556 } else { // Use the string from the pre-built list.
2557 searchURL = torSearchString;
2560 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2561 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2563 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2565 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2567 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2570 // Display a message to the user if we are waiting on Orbot.
2571 if (!orbotStatus.equals("ON")) {
2572 // Set `waitingForOrbot`.
2573 waitingForOrbot = true;
2575 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2576 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2578 } else { // Set the non-Tor options.
2579 // Set `homepageString` as `homepage`.
2580 homepage = homepageString;
2582 // If formattedUrlString is null assign the homepage to it.
2583 if (formattedUrlString == null) {
2584 formattedUrlString = homepage;
2587 // Set the search URL.
2588 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2589 searchURL = searchCustomURLString;
2590 } else { // Use the string from the pre-built list.
2591 searchURL = searchString;
2594 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2595 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2597 // Set the default `appBar` background. `this` refers to the context.
2599 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2601 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2604 // Reset `waitingForOrbot.
2605 waitingForOrbot = false;
2608 // Set swipe to refresh.
2609 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2611 // Set Do Not Track status.
2612 if (doNotTrackEnabled) {
2613 customHeaders.put("DNT", "1");
2615 customHeaders.remove("DNT");
2618 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2619 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2620 if (hideSystemBarsOnFullscreen) { // Hide everything.
2621 // Remove the translucent navigation setting if it is currently flagged.
2622 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2624 // Remove the translucent status bar overlay.
2625 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2627 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2628 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2630 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2631 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2632 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2634 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2635 } else { // Hide everything except the status and navigation bars.
2636 // Add the translucent status flag if it is unset.
2637 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2639 if (translucentNavigationBarOnFullscreen) {
2640 // Set the navigation bar to be translucent.
2641 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2643 // Set the navigation bar to be black.
2644 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2647 } else { // Switch to normal viewing mode.
2648 // Reset `inFullScreenBrowsingMode` to `false`.
2649 inFullScreenBrowsingMode = false;
2651 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2652 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2656 // Show the `BannerAd` in the free flavor.
2657 if (BuildConfig.FLAVOR.contentEquals("free")) {
2658 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2659 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2661 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2662 adView = findViewById(R.id.adview);
2665 // Remove the translucent navigation bar flag if it is set.
2666 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2668 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2669 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2671 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2672 rootCoordinatorLayout.setSystemUiVisibility(0);
2674 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2675 rootCoordinatorLayout.setFitsSystemWindows(true);
2679 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2680 @SuppressWarnings("deprecation")
2681 private void applyDomainSettings(String url) {
2682 // Reset `navigatingHistory`.
2683 navigatingHistory = false;
2685 // Parse the URL into a URI.
2686 Uri uri = Uri.parse(url);
2688 // Extract the domain from `uri`.
2689 String hostName = uri.getHost();
2691 // Initialize `loadingNewDomainName`.
2692 boolean loadingNewDomainName;
2694 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2695 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2696 //noinspection SimplifiableIfStatement
2697 if ((hostName == null) || (currentDomainName == null)) {
2698 loadingNewDomainName = true;
2699 } else { // Determine if `hostName` equals `currentDomainName`.
2700 loadingNewDomainName = !hostName.equals(currentDomainName);
2703 // 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.
2704 if (loadingNewDomainName) {
2705 // Set the new `hostname` as the `currentDomainName`.
2706 currentDomainName = hostName;
2708 // Reset `ignorePinnedSslCertificate`.
2709 ignorePinnedSslCertificate = false;
2711 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2712 favoriteIconBitmap = favoriteIconDefaultBitmap;
2713 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2715 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2716 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2717 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2719 // Get a full cursor from `domainsDatabaseHelper`.
2720 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2722 // Initialize `domainSettingsSet`.
2723 Set<String> domainSettingsSet = new HashSet<>();
2725 // Get the domain name column index.
2726 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2728 // Populate `domainSettingsSet`.
2729 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2730 // Move `domainsCursor` to the current row.
2731 domainNameCursor.moveToPosition(i);
2733 // Store the domain name in `domainSettingsSet`.
2734 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2737 // Close `domainNameCursor.
2738 domainNameCursor.close();
2740 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2741 domainSettingsApplied = false;
2742 String domainNameInDatabase = null;
2744 // Check the hostname.
2745 if (domainSettingsSet.contains(hostName)) {
2746 domainSettingsApplied = true;
2747 domainNameInDatabase = hostName;
2750 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2751 if (hostName != null) {
2752 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2753 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2754 domainSettingsApplied = true;
2755 domainNameInDatabase = "*." + hostName;
2758 // Strip out the lowest subdomain of `host`.
2759 hostName = hostName.substring(hostName.indexOf(".") + 1);
2763 // Get a handle for the shared preference. `this` references the current context.
2764 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2766 // Store the general preference information.
2767 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2768 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2769 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2770 nightMode = sharedPreferences.getBoolean("night_mode", false);
2772 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2773 // Get a cursor for the current host and move it to the first position.
2774 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2775 currentHostDomainSettingsCursor.moveToFirst();
2777 // Get the settings from the cursor.
2778 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
2779 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2780 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2781 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2782 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2783 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2784 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2785 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2786 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2787 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
2788 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
2789 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
2790 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
2791 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
2792 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
2793 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
2794 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
2796 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
2797 switch (nightModeInt) {
2798 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
2802 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
2807 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
2809 javaScriptEnabled = true;
2812 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
2813 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
2814 pinnedDomainSslStartDate = null;
2816 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
2819 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
2820 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
2821 pinnedDomainSslEndDate = null;
2823 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
2826 // Close `currentHostDomainSettingsCursor`.
2827 currentHostDomainSettingsCursor.close();
2829 // Apply the domain settings.
2830 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2831 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2832 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2833 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2835 // Apply the font size.
2836 if (fontSize == 0) { // Apply the default font size.
2837 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2838 } else { // Apply the specified font size.
2839 mainWebView.getSettings().setTextZoom(fontSize);
2842 // Set third-party cookies status if API >= 21.
2843 if (Build.VERSION.SDK_INT >= 21) {
2844 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2847 // 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>
2848 if (!urlIsLoading) {
2849 switch (userAgentString) {
2850 case "System default user agent":
2851 // Set the user agent according to the system default.
2852 switch (defaultUserAgentString) {
2853 case "WebView default user agent":
2854 // Set the user agent to `""`, which uses the default value.
2855 mainWebView.getSettings().setUserAgentString("");
2858 case "Custom user agent":
2859 // Set the custom user agent.
2860 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2864 // Use the selected user agent.
2865 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2869 case "WebView default user agent":
2870 // Set the user agent to `""`, which uses the default value.
2871 mainWebView.getSettings().setUserAgentString("");
2875 // Use the selected user agent.
2876 mainWebView.getSettings().setUserAgentString(userAgentString);
2880 // 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.
2882 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
2884 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
2886 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2887 // Store the values from `sharedPreferences` in variables.
2888 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2889 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2890 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2891 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2892 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2894 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
2896 javaScriptEnabled = true;
2899 // Apply the default settings.
2900 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2901 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2902 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2903 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2904 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2906 // Reset the pinned SSL certificate information.
2907 domainSettingsDatabaseId = -1;
2908 pinnedDomainSslCertificate = false;
2909 pinnedDomainSslIssuedToCNameString = "";
2910 pinnedDomainSslIssuedToONameString = "";
2911 pinnedDomainSslIssuedToUNameString = "";
2912 pinnedDomainSslIssuedByCNameString = "";
2913 pinnedDomainSslIssuedByONameString = "";
2914 pinnedDomainSslIssuedByUNameString = "";
2915 pinnedDomainSslStartDate = null;
2916 pinnedDomainSslEndDate = null;
2918 // Set third-party cookies status if API >= 21.
2919 if (Build.VERSION.SDK_INT >= 21) {
2920 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2923 // 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>
2924 if (!urlIsLoading) {
2925 switch (defaultUserAgentString) {
2926 case "WebView default user agent":
2927 // Set the user agent to `""`, which uses the default value.
2928 mainWebView.getSettings().setUserAgentString("");
2931 case "Custom user agent":
2932 // Set the custom user agent.
2933 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2937 // Use the selected user agent.
2938 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2942 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2943 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
2946 // Close `domainsDatabaseHelper`.
2947 domainsDatabaseHelper.close();
2949 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2950 onTheFlyDisplayImagesSet = false;
2951 setDisplayWebpageImages();
2953 // Update the privacy icons, but only if `mainMenu` has already been populated.
2954 if (mainMenu != null) {
2955 updatePrivacyIcons(true);
2960 private void setDisplayWebpageImages() {
2961 if (!onTheFlyDisplayImagesSet) {
2962 if (domainSettingsApplied) { // Custom domain settings are applied.
2963 switch (displayWebpageImagesInt) {
2964 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2965 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2968 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2969 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2972 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2973 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2976 } else { // Default settings are applied.
2977 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2982 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2983 // Get handles for the icons.
2984 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2985 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2986 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2987 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2989 // Update `privacyIcon`.
2990 if (javaScriptEnabled) { // JavaScript is enabled.
2991 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2992 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2993 privacyIconMenuItem.setIcon(R.drawable.warning);
2994 } else { // All the dangerous features are disabled.
2995 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2998 // Update `firstPartyCookiesIcon`.
2999 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
3000 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
3001 } else { // First-party cookies are disabled.
3003 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3005 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3009 // Update `domStorageIcon`.
3010 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3011 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3012 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3014 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3016 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3018 } else { // JavaScript is disabled, so DOM storage is ghosted.
3020 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3022 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3026 // Update `formDataIcon`.
3027 if (saveFormDataEnabled) { // Form data is enabled.
3028 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3029 } else { // Form data is disabled.
3031 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3033 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3037 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
3038 if (runInvalidateOptionsMenu) {
3039 ActivityCompat.invalidateOptionsMenu(this);
3043 private void highlightUrlText() {
3044 String urlString = urlTextBox.getText().toString();
3046 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
3047 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3048 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
3049 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3052 // Get the index of the `/` immediately after the domain name.
3053 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3055 // De-emphasize the text after the domain name.
3056 if (endOfDomainName > 0) {
3057 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3061 private void loadBookmarksFolder() {
3062 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3063 Cursor bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3065 // Setup a `CursorAdapter`. `this` specifies the `Context`. `false` disables `autoRequery`.
3066 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3068 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3069 // Inflate the individual item layout. `false` does not attach it to the root.
3070 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3074 public void bindView(View view, Context context, Cursor cursor) {
3075 // Get handles for the views.
3076 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
3077 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
3079 // Get the favorite icon byte array from the `Cursor`.
3080 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3082 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3083 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3085 // Display the bitmap in `bookmarkFavoriteIcon`.
3086 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3088 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3089 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3090 bookmarkNameTextView.setText(bookmarkNameString);
3092 // Make the font bold for folders.
3093 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3094 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3095 } else { // Reset the font to default for normal bookmarks.
3096 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3101 // Populate the `ListView` with the adapter.
3102 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3104 // Set the bookmarks drawer title.
3105 if (currentBookmarksFolder.isEmpty()) {
3106 bookmarksTitleTextView.setText(R.string.bookmarks);
3108 bookmarksTitleTextView.setText(currentBookmarksFolder);