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 // Get the bookmark URL and assign it to `formattedUrlString`.
686 String bookmarkUrl = bookmarkCursor.getString(bookmarkCursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_URL));
688 // Load the bookmark URL.
689 loadUrl(bookmarkUrl);
691 // Close the bookmarks drawer.
692 drawerLayout.closeDrawer(GravityCompat.END);
695 // Close the `Cursor`.
696 bookmarkCursor.close();
700 // The `DrawerListener` allows us to update the Navigation Menu.
701 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
703 public void onDrawerSlide(View drawerView, float slideOffset) {
707 public void onDrawerOpened(View drawerView) {
711 public void onDrawerClosed(View drawerView) {
715 public void onDrawerStateChanged(int newState) {
716 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
717 // Update the `Back`, `Forward`, and `History` menu items.
718 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
719 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
720 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
722 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
723 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
725 // Clear the focus from `urlTextBox` if it has it.
726 urlTextBox.clearFocus();
731 // drawerToggle creates the hamburger icon at the start of the AppBar.
732 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
734 // Initialize `adServerSet`.
735 final Set<String> adServersSet = new HashSet<>();
737 // Load the list of ad servers into memory.
739 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
740 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
742 // Create a string for storing each ad server.
745 // Populate `adServersSet`.
746 while ((adServer = bufferedReader.readLine()) != null) {
747 adServersSet.add(adServer);
750 // Close `bufferedReader`.
751 bufferedReader.close();
752 } catch (IOException ioException) {
753 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
756 mainWebView.setWebViewClient(new WebViewClient() {
757 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
758 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
759 @SuppressWarnings("deprecation")
761 public boolean shouldOverrideUrlLoading(WebView view, String url) {
762 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
763 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
764 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
766 // Parse the url and set it as the data for the `Intent`.
767 emailIntent.setData(Uri.parse(url));
769 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
770 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
773 startActivity(emailIntent);
775 // Returning `true` indicates the application is handling the URL.
777 } else { // Load the URL in Privacy Browser.
778 // Apply the domain settings for the new URL.
779 applyDomainSettings(url);
781 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
786 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
787 @SuppressWarnings("deprecation")
789 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
790 if (adBlockerEnabled) { // Block ads.
791 // Extract the host from `url`.
792 Uri requestUri = Uri.parse(url);
793 String requestHost = requestUri.getHost();
795 // Initialize a variable to track if this is an ad server.
796 boolean requestHostIsAdServer = false;
798 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
799 if (requestHost != null) {
800 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
801 if (adServersSet.contains(requestHost)) {
802 requestHostIsAdServer = true;
805 // Strip out the lowest subdomain of `requestHost`.
806 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
810 if (requestHostIsAdServer) { // It is an ad server.
811 // Return an empty `WebResourceResponse`.
812 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
813 } else { // It is not an ad server.
814 // `return null` loads the requested resource.
817 } else { // Ad blocking is disabled.
818 // `return null` loads the requested resource.
823 // Handle HTTP authentication requests.
825 public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
826 // Store `handler` so it can be accessed from `onHttpAuthenticationCancel()` and `onHttpAuthenticationProceed()`.
827 httpAuthHandler = handler;
829 // Display the HTTP authentication dialog.
830 AppCompatDialogFragment httpAuthenticationDialogFragment = HttpAuthenticationDialog.displayDialog(host, realm);
831 httpAuthenticationDialogFragment.show(getSupportFragmentManager(), getString(R.string.http_authentication));
834 // Update the URL in urlTextBox when the page starts to load.
836 public void onPageStarted(WebView view, String url, Bitmap favicon) {
837 // If night mode is enabled, hide `mainWebView` until after the night mode CSS is applied.
839 mainWebView.setVisibility(View.INVISIBLE);
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 progressBar.setProgress(progress);
1025 if (progress < 100) {
1026 // Show the progress bar.
1027 progressBar.setVisibility(View.VISIBLE);
1029 // Hide the progress bar.
1030 progressBar.setVisibility(View.GONE);
1032 // Inject the night mode CSS if night mode is enabled.
1033 if (nightMode) { // Night mode is enabled.
1034 // `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.
1035 // `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.
1036 // `a {color: #1565C0}` sets links to be a dark blue. `!important` takes precedent over any existing sub-settings.
1037 mainWebView.evaluateJavascript("(function() {var parent = document.getElementsByTagName('head').item(0); var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = '" +
1038 "* {background-color: #212121 !important; color: #BDBDBD !important; box-shadow: none !important; text-decoration: none !important; text-shadow: none !important; border: none !important;}" +
1039 "a {color: #1565C0 !important;}" +
1040 "'; parent.appendChild(style)})()", new ValueCallback<String>() {
1042 public void onReceiveValue(String value) {
1043 // Initialize a `Handler` to display `mainWebView`.
1044 Handler displayWebViewHandler = new Handler();
1046 // Setup a `Runnable` to display `mainWebView` after a delay to allow the CSS to be applied.
1047 Runnable displayWebViewRunnable = new Runnable() {
1049 mainWebView.setVisibility(View.VISIBLE);
1053 // Use `displayWebViewHandler` to delay the displaying of `mainWebView` for 500 milliseconds.
1054 displayWebViewHandler.postDelayed(displayWebViewRunnable, 500);
1057 } else { // Night mode is disabled.
1058 // Display `mainWebView` in case it was hidden before loading domain settings.
1059 mainWebView.setVisibility(View.VISIBLE);
1062 //Stop the `SwipeToRefresh` indicator if it is running
1063 swipeRefreshLayout.setRefreshing(false);
1067 // Set the favorite icon when it changes.
1069 public void onReceivedIcon(WebView view, Bitmap icon) {
1070 // Only update the favorite icon if the website has finished loading.
1071 if (progressBar.getVisibility() == View.GONE) {
1072 // Save a copy of the favorite icon.
1073 favoriteIconBitmap = icon;
1075 // Place the favorite icon in the appBar.
1076 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
1080 // Save a copy of the title when it changes.
1082 public void onReceivedTitle(WebView view, String title) {
1083 // Save a copy of the title.
1084 webViewTitle = title;
1087 // Enter full screen video
1089 public void onShowCustomView(View view, CustomViewCallback callback) {
1090 // Pause the ad if this is the free flavor.
1091 if (BuildConfig.FLAVOR.contentEquals("free")) {
1092 BannerAd.pauseAd(adView);
1095 // Remove the translucent overlays.
1096 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1098 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1099 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1101 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1102 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1103 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1105 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1107 // Set `rootCoordinatorLayout` to fill the entire screen.
1108 rootCoordinatorLayout.setFitsSystemWindows(false);
1110 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
1111 fullScreenVideoFrameLayout.addView(view);
1112 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
1115 // Exit full screen video
1116 public void onHideCustomView() {
1117 // Hide `fullScreenVideoFrameLayout`.
1118 fullScreenVideoFrameLayout.removeAllViews();
1119 fullScreenVideoFrameLayout.setVisibility(View.GONE);
1121 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
1122 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1124 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
1125 rootCoordinatorLayout.setFitsSystemWindows(true);
1127 // Show the ad if this is the free flavor.
1128 if (BuildConfig.FLAVOR.contentEquals("free")) {
1129 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
1130 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1132 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1133 adView = findViewById(R.id.adview);
1138 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
1139 registerForContextMenu(mainWebView);
1141 // Allow the downloading of files.
1142 mainWebView.setDownloadListener(new DownloadListener() {
1144 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
1145 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
1146 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
1147 downloadFileDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
1151 // Allow pinch to zoom.
1152 mainWebView.getSettings().setBuiltInZoomControls(true);
1154 // Hide zoom controls.
1155 mainWebView.getSettings().setDisplayZoomControls(false);
1157 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
1158 mainWebView.getSettings().setUseWideViewPort(true);
1160 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
1161 mainWebView.getSettings().setLoadWithOverviewMode(true);
1163 // Explicitly disable geolocation.
1164 mainWebView.getSettings().setGeolocationEnabled(false);
1166 // Initialize cookieManager.
1167 cookieManager = CookieManager.getInstance();
1169 // 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).
1170 customHeaders.put("X-Requested-With", "");
1172 // 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.
1173 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
1175 // Get the intent that started the app.
1176 final Intent launchingIntent = getIntent();
1178 // Extract the launching intent data as `launchingIntentUriData`.
1179 final Uri launchingIntentUriData = launchingIntent.getData();
1181 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
1182 if (launchingIntentUriData != null) {
1183 formattedUrlString = launchingIntentUriData.toString();
1186 // Get a handle for the `Runtime`.
1187 privacyBrowserRuntime = Runtime.getRuntime();
1189 // Store the application's private data directory.
1190 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`.
1192 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
1193 inFullScreenBrowsingMode = false;
1195 // Initialize AdView for the free flavor.
1196 adView = findViewById(R.id.adview);
1198 // Initialize the privacy settings variables.
1199 javaScriptEnabled = false;
1200 firstPartyCookiesEnabled = false;
1201 thirdPartyCookiesEnabled = false;
1202 domStorageEnabled = false;
1203 saveFormDataEnabled = false;
1206 // Initialize `webViewTitle`.
1207 webViewTitle = getString(R.string.no_title);
1209 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
1210 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
1211 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
1212 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
1214 // If the favorite icon is null, load the default.
1215 if (favoriteIconBitmap == null) {
1216 favoriteIconBitmap = favoriteIconDefaultBitmap;
1219 // Apply the app settings from the shared preferences.
1222 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
1223 if (!waitingForOrbot) {
1224 loadUrl(formattedUrlString);
1229 protected void onNewIntent(Intent intent) {
1230 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
1233 if (intent.getData() != null) {
1234 // Get the intent data and convert it to a string.
1235 final Uri intentUriData = intent.getData();
1236 formattedUrlString = intentUriData.toString();
1239 // Close the navigation drawer if it is open.
1240 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1241 drawerLayout.closeDrawer(GravityCompat.START);
1244 // Load the website.
1245 loadUrl(formattedUrlString);
1247 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1248 mainWebView.requestFocus();
1252 public void onRestart() {
1255 // Apply the app settings, which may have been changed in `SettingsActivity`.
1258 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1259 updatePrivacyIcons(true);
1261 // Set the display webpage images mode.
1262 setDisplayWebpageImages();
1264 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1265 if (reloadOnRestart) {
1266 // Reload `mainWebView`.
1267 mainWebView.reload();
1269 // Reset `reloadOnRestartBoolean`.
1270 reloadOnRestart = false;
1273 // Load the URL on restart to apply changes to night mode.
1274 if (loadUrlOnRestart) {
1275 // Load the current `formattedUrlString`.
1276 loadUrl(formattedUrlString);
1278 // Reset `loadUrlOnRestart.
1279 loadUrlOnRestart = false;
1283 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1285 public void onResume() {
1288 // Resume JavaScript (if enabled).
1289 mainWebView.resumeTimers();
1291 // Resume `mainWebView`.
1292 mainWebView.onResume();
1294 // Resume the adView for the free flavor.
1295 if (BuildConfig.FLAVOR.contentEquals("free")) {
1296 BannerAd.resumeAd(adView);
1301 public void onPause() {
1302 // Pause `mainWebView`.
1303 mainWebView.onPause();
1305 // Stop all JavaScript.
1306 mainWebView.pauseTimers();
1308 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1309 if (BuildConfig.FLAVOR.contentEquals("free")) {
1310 BannerAd.pauseAd(adView);
1317 public boolean onCreateOptionsMenu(Menu menu) {
1318 // Inflate the menu; this adds items to the action bar if it is present.
1319 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1321 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1324 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1325 updatePrivacyIcons(false);
1327 // Get handles for the menu items.
1328 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1329 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1330 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1331 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1333 // Only display third-party cookies if SDK >= 21
1334 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1336 // Get the shared preference values. `this` references the current context.
1337 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1339 // Set the status of the additional app bar icons. The default is `false`.
1340 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1341 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1342 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1343 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1344 } else { //Do not display the additional icons.
1345 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1346 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1347 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1354 public boolean onPrepareOptionsMenu(Menu menu) {
1355 // Get handles for the menu items.
1356 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1357 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1358 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1359 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1360 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1361 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1362 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1363 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1364 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1365 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1367 // Set the status of the menu item checkboxes.
1368 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1369 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1370 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1371 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1372 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1374 // Enable third-party cookies if first-party cookies are enabled.
1375 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1377 // Enable `DOM Storage` if JavaScript is enabled.
1378 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1380 // Enable `Clear Cookies` if there are any.
1381 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1383 // Get a count of the number of files in the `Local Storage` directory.
1384 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1385 int localStorageDirectoryNumberOfFiles = 0;
1386 if (localStorageDirectory.exists()) {
1387 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1390 // Get a count of the number of files in the `IndexedDB` directory.
1391 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1392 int indexedDBDirectoryNumberOfFiles = 0;
1393 if (indexedDBDirectory.exists()) {
1394 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1397 // Enable `Clear DOM Storage` if there is any.
1398 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1400 // Enable `Clear Form Data` is there is any.
1401 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1402 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1404 // Initialize font size variables.
1405 int fontSize = mainWebView.getSettings().getTextZoom();
1406 String fontSizeTitle;
1407 MenuItem selectedFontSizeMenuItem;
1409 // Prepare the font size title and current size menu item.
1412 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.twenty_five_percent);
1413 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1417 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.fifty_percent);
1418 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1422 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.seventy_five_percent);
1423 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1427 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1428 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1432 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_twenty_five_percent);
1433 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1437 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_fifty_percent);
1438 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1442 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_seventy_five_percent);
1443 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1447 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.two_hundred_percent);
1448 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1452 fontSizeTitle = getString(R.string.font_size) + " - " + getString(R.string.one_hundred_percent);
1453 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1457 // Set the font size title and select the current size menu item.
1458 fontSizeMenuItem.setTitle(fontSizeTitle);
1459 selectedFontSizeMenuItem.setChecked(true);
1461 // Only show `Refresh` if `swipeToRefresh` is disabled.
1462 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1464 // Run all the other default commands.
1465 super.onPrepareOptionsMenu(menu);
1467 // `return true` displays the menu.
1472 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1473 @SuppressLint("SetJavaScriptEnabled")
1474 // removeAllCookies is deprecated, but it is required for API < 21.
1475 @SuppressWarnings("deprecation")
1476 public boolean onOptionsItemSelected(MenuItem menuItem) {
1477 int menuItemId = menuItem.getItemId();
1479 // Set the commands that relate to the menu entries.
1480 switch (menuItemId) {
1481 case R.id.toggle_javascript:
1482 // Switch the status of javaScriptEnabled.
1483 javaScriptEnabled = !javaScriptEnabled;
1485 // Apply the new JavaScript status.
1486 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1488 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1489 updatePrivacyIcons(true);
1491 // Display a `Snackbar`.
1492 if (javaScriptEnabled) { // JavaScrip is enabled.
1493 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1494 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1495 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1496 } else { // Privacy mode.
1497 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1500 // Reload the WebView.
1501 mainWebView.reload();
1504 case R.id.toggle_first_party_cookies:
1505 // Switch the status of firstPartyCookiesEnabled.
1506 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1508 // Update the menu checkbox.
1509 menuItem.setChecked(firstPartyCookiesEnabled);
1511 // Apply the new cookie status.
1512 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1514 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1515 updatePrivacyIcons(true);
1517 // Display a `Snackbar`.
1518 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1519 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1520 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1521 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1522 } else { // Privacy mode.
1523 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1526 // Reload the WebView.
1527 mainWebView.reload();
1530 case R.id.toggle_third_party_cookies:
1531 if (Build.VERSION.SDK_INT >= 21) {
1532 // Switch the status of thirdPartyCookiesEnabled.
1533 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1535 // Update the menu checkbox.
1536 menuItem.setChecked(thirdPartyCookiesEnabled);
1538 // Apply the new cookie status.
1539 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1541 // Display a `Snackbar`.
1542 if (thirdPartyCookiesEnabled) {
1543 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1545 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1548 // Reload the WebView.
1549 mainWebView.reload();
1550 } // Else do nothing because SDK < 21.
1553 case R.id.toggle_dom_storage:
1554 // Switch the status of domStorageEnabled.
1555 domStorageEnabled = !domStorageEnabled;
1557 // Update the menu checkbox.
1558 menuItem.setChecked(domStorageEnabled);
1560 // Apply the new DOM Storage status.
1561 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1563 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1564 updatePrivacyIcons(true);
1566 // Display a `Snackbar`.
1567 if (domStorageEnabled) {
1568 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1570 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1573 // Reload the WebView.
1574 mainWebView.reload();
1577 case R.id.toggle_save_form_data:
1578 // Switch the status of saveFormDataEnabled.
1579 saveFormDataEnabled = !saveFormDataEnabled;
1581 // Update the menu checkbox.
1582 menuItem.setChecked(saveFormDataEnabled);
1584 // Apply the new form data status.
1585 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1587 // Display a `Snackbar`.
1588 if (saveFormDataEnabled) {
1589 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1591 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1594 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1595 updatePrivacyIcons(true);
1597 // Reload the WebView.
1598 mainWebView.reload();
1601 case R.id.clear_cookies:
1602 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1603 .setAction(R.string.undo, new View.OnClickListener() {
1605 public void onClick(View v) {
1606 // Do nothing because everything will be handled by `onDismissed()` below.
1609 .addCallback(new Snackbar.Callback() {
1611 public void onDismissed(Snackbar snackbar, int event) {
1613 // The user pushed the `Undo` button.
1614 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1618 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1620 // `cookieManager.removeAllCookie()` varies by SDK.
1621 if (Build.VERSION.SDK_INT < 21) {
1622 cookieManager.removeAllCookie();
1624 // `null` indicates no callback.
1625 cookieManager.removeAllCookies(null);
1633 case R.id.clear_dom_storage:
1634 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1635 .setAction(R.string.undo, new View.OnClickListener() {
1637 public void onClick(View v) {
1638 // Do nothing because everything will be handled by `onDismissed()` below.
1641 .addCallback(new Snackbar.Callback() {
1643 public void onDismissed(Snackbar snackbar, int event) {
1645 // The user pushed the `Undo` button.
1646 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1650 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1652 // Delete the DOM Storage.
1653 WebStorage webStorage = WebStorage.getInstance();
1654 webStorage.deleteAllData();
1656 // Manually remove `IndexedDB` if it exists.
1658 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1659 } catch (IOException e) {
1660 // Do nothing if an error is thrown.
1668 case R.id.clear_form_data:
1669 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1670 .setAction(R.string.undo, new View.OnClickListener() {
1672 public void onClick(View v) {
1673 // Do nothing because everything will be handled by `onDismissed()` below.
1676 .addCallback(new Snackbar.Callback() {
1678 public void onDismissed(Snackbar snackbar, int event) {
1680 // The user pushed the `Undo` button.
1681 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1685 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1687 // Delete the form data.
1688 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1689 mainWebViewDatabase.clearFormData();
1696 case R.id.font_size_twenty_five_percent:
1697 mainWebView.getSettings().setTextZoom(25);
1700 case R.id.font_size_fifty_percent:
1701 mainWebView.getSettings().setTextZoom(50);
1704 case R.id.font_size_seventy_five_percent:
1705 mainWebView.getSettings().setTextZoom(75);
1708 case R.id.font_size_one_hundred_percent:
1709 mainWebView.getSettings().setTextZoom(100);
1712 case R.id.font_size_one_hundred_twenty_five_percent:
1713 mainWebView.getSettings().setTextZoom(125);
1716 case R.id.font_size_one_hundred_fifty_percent:
1717 mainWebView.getSettings().setTextZoom(150);
1720 case R.id.font_size_one_hundred_seventy_five_percent:
1721 mainWebView.getSettings().setTextZoom(175);
1724 case R.id.font_size_two_hundred_percent:
1725 mainWebView.getSettings().setTextZoom(200);
1728 case R.id.display_images:
1729 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1730 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1731 mainWebView.reload();
1732 } else { // Images are not currently loaded automatically.
1733 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1736 // Set `onTheFlyDisplayImagesSet`.
1737 onTheFlyDisplayImagesSet = true;
1741 // Setup the share string.
1742 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1744 // Create the share intent.
1745 Intent shareIntent = new Intent();
1746 shareIntent.setAction(Intent.ACTION_SEND);
1747 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1748 shareIntent.setType("text/plain");
1751 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1754 case R.id.find_on_page:
1755 // Hide the URL app bar.
1756 supportAppBar.setVisibility(View.GONE);
1758 // Show the Find on Page `RelativeLayout`.
1759 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1761 // 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
1762 findOnPageEditText.postDelayed(new Runnable() {
1766 // Set the focus on `findOnPageEditText`.
1767 findOnPageEditText.requestFocus();
1769 // Display the keyboard. `0` sets no input flags.
1770 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1776 // Get a `PrintManager` instance.
1777 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1779 // Convert `mainWebView` to `printDocumentAdapter`.
1780 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1782 // Print the document. The print attributes are `null`.
1783 printManager.print(getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1786 case R.id.add_to_homescreen:
1787 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1788 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1789 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getString(R.string.create_shortcut));
1791 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1795 mainWebView.reload();
1799 // Don't consume the event.
1800 return super.onOptionsItemSelected(menuItem);
1804 // removeAllCookies is deprecated, but it is required for API < 21.
1805 @SuppressWarnings("deprecation")
1807 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1808 int menuItemId = menuItem.getItemId();
1810 switch (menuItemId) {
1816 if (mainWebView.canGoBack()) {
1817 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1818 navigatingHistory = true;
1820 // Load the previous website in the history.
1821 mainWebView.goBack();
1826 if (mainWebView.canGoForward()) {
1827 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1828 navigatingHistory = true;
1830 // Load the next website in the history.
1831 mainWebView.goForward();
1836 // Get the `WebBackForwardList`.
1837 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1839 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1840 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1841 urlHistoryDialogFragment.show(getSupportFragmentManager(), getString(R.string.history));
1844 case R.id.bookmarks:
1845 // Launch BookmarksActivity.
1846 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1847 startActivity(bookmarksIntent);
1850 case R.id.downloads:
1851 // Launch the system Download Manager.
1852 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1854 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1855 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1857 startActivity(downloadManagerIntent);
1861 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1862 currentDomainName = "";
1864 // Launch `SettingsActivity`.
1865 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1866 startActivity(settingsIntent);
1870 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1871 currentDomainName = "";
1873 // Launch `DomainsActivity`.
1874 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1875 startActivity(domainsIntent);
1879 // Launch `GuideActivity`.
1880 Intent guideIntent = new Intent(this, GuideActivity.class);
1881 startActivity(guideIntent);
1885 // Launch `AboutActivity`.
1886 Intent aboutIntent = new Intent(this, AboutActivity.class);
1887 startActivity(aboutIntent);
1890 case R.id.clearAndExit:
1891 // Get a handle for `sharedPreferences`. `this` references the current context.
1892 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1894 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1897 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1898 // The command to remove cookies changed slightly in API 21.
1899 if (Build.VERSION.SDK_INT >= 21) {
1900 cookieManager.removeAllCookies(null);
1902 cookieManager.removeAllCookie();
1905 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1907 // We have to use two commands because `Runtime.exec()` does not like `*`.
1908 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1909 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1910 } catch (IOException e) {
1911 // Do nothing if an error is thrown.
1915 // Clear DOM storage.
1916 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1917 // Ask `WebStorage` to clear the DOM storage.
1918 WebStorage webStorage = WebStorage.getInstance();
1919 webStorage.deleteAllData();
1921 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1923 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1924 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1926 // We have to use multiple commands because `Runtime.exec()` does not like `*`.
1927 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1928 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1929 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1930 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1931 } catch (IOException e) {
1932 // Do nothing if an error is thrown.
1937 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1938 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1939 webViewDatabase.clearFormData();
1941 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1943 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1944 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1945 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1946 } catch (IOException e) {
1947 // Do nothing if an error is thrown.
1952 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1953 // `true` includes disk files.
1954 mainWebView.clearCache(true);
1956 // Manually delete the cache directories.
1958 // Delete the main cache directory.
1959 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1961 // 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.
1962 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1963 } catch (IOException e) {
1964 // Do nothing if an error is thrown.
1968 // Clear SSL certificate preferences.
1969 mainWebView.clearSslPreferences();
1971 // Clear the back/forward history.
1972 mainWebView.clearHistory();
1974 // Clear `formattedUrlString`.
1975 formattedUrlString = null;
1977 // Clear `customHeaders`.
1978 customHeaders.clear();
1980 // Detach all views from `mainWebViewRelativeLayout`.
1981 mainWebViewRelativeLayout.removeAllViews();
1983 // Destroy the internal state of `mainWebView`.
1984 mainWebView.destroy();
1986 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1987 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1988 if (clearEverything) {
1990 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1991 } catch (IOException e) {
1992 // Do nothing if an error is thrown.
1996 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1997 if (Build.VERSION.SDK_INT >= 21) {
1998 finishAndRemoveTask();
2003 // Remove the terminated program from RAM. The status code is `0`.
2008 // Close the navigation drawer.
2009 drawerLayout.closeDrawer(GravityCompat.START);
2014 public void onPostCreate(Bundle savedInstanceState) {
2015 super.onPostCreate(savedInstanceState);
2017 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
2018 drawerToggle.syncState();
2022 public void onConfigurationChanged(Configuration newConfig) {
2023 super.onConfigurationChanged(newConfig);
2025 // Reload the ad for the free flavor if we are not in full screen mode.
2026 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
2028 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2030 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2031 adView = findViewById(R.id.adview);
2034 // `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
2035 // ActivityCompat.invalidateOptionsMenu(this);
2039 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
2040 // Store the `HitTestResult`.
2041 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
2044 final String imageUrl;
2045 final String linkUrl;
2047 // Get a handle for the `ClipboardManager`.
2048 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
2050 switch (hitTestResult.getType()) {
2051 // `SRC_ANCHOR_TYPE` is a link.
2052 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
2053 // Get the target URL.
2054 linkUrl = hitTestResult.getExtra();
2056 // Set the target URL as the title of the `ContextMenu`.
2057 menu.setHeaderTitle(linkUrl);
2059 // Add a `Load URL` entry.
2060 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2062 public boolean onMenuItemClick(MenuItem item) {
2068 // Add a `Copy URL` entry.
2069 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2071 public boolean onMenuItemClick(MenuItem item) {
2072 // Save the link URL in a `ClipData`.
2073 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), linkUrl);
2075 // Set the `ClipData` as the clipboard's primary clip.
2076 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
2081 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2082 menu.add(R.string.cancel);
2085 case WebView.HitTestResult.EMAIL_TYPE:
2086 // Get the target URL.
2087 linkUrl = hitTestResult.getExtra();
2089 // Set the target URL as the title of the `ContextMenu`.
2090 menu.setHeaderTitle(linkUrl);
2092 // Add a `Write Email` entry.
2093 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2095 public boolean onMenuItemClick(MenuItem item) {
2096 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
2097 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
2099 // Parse the url and set it as the data for the `Intent`.
2100 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
2102 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
2103 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2106 startActivity(emailIntent);
2111 // Add a `Copy Email Address` entry.
2112 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2114 public boolean onMenuItemClick(MenuItem item) {
2115 // Save the email address in a `ClipData`.
2116 ClipData srcEmailTypeClipData = ClipData.newPlainText(getString(R.string.email_address), linkUrl);
2118 // Set the `ClipData` as the clipboard's primary clip.
2119 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
2124 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2125 menu.add(R.string.cancel);
2128 // `IMAGE_TYPE` is an image.
2129 case WebView.HitTestResult.IMAGE_TYPE:
2130 // Get the image URL.
2131 imageUrl = hitTestResult.getExtra();
2133 // Set the image URL as the title of the `ContextMenu`.
2134 menu.setHeaderTitle(imageUrl);
2136 // Add a `View Image` entry.
2137 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2139 public boolean onMenuItemClick(MenuItem item) {
2145 // Add a `Download Image` entry.
2146 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2148 public boolean onMenuItemClick(MenuItem item) {
2149 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2150 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2151 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2156 // Add a `Copy URL` entry.
2157 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2159 public boolean onMenuItemClick(MenuItem item) {
2160 // Save the image URL in a `ClipData`.
2161 ClipData srcImageTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2163 // Set the `ClipData` as the clipboard's primary clip.
2164 clipboardManager.setPrimaryClip(srcImageTypeClipData);
2169 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2170 menu.add(R.string.cancel);
2174 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
2175 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
2176 // Get the image URL.
2177 imageUrl = hitTestResult.getExtra();
2179 // Set the image URL as the title of the `ContextMenu`.
2180 menu.setHeaderTitle(imageUrl);
2182 // Add a `View Image` entry.
2183 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2185 public boolean onMenuItemClick(MenuItem item) {
2191 // Add a `Download Image` entry.
2192 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2194 public boolean onMenuItemClick(MenuItem item) {
2195 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
2196 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
2197 downloadImageDialogFragment.show(getSupportFragmentManager(), getString(R.string.download));
2202 // Add a `Copy URL` entry.
2203 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
2205 public boolean onMenuItemClick(MenuItem item) {
2206 // Save the image URL in a `ClipData`.
2207 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getString(R.string.url), imageUrl);
2209 // Set the `ClipData` as the clipboard's primary clip.
2210 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
2215 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
2216 menu.add(R.string.cancel);
2222 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
2223 // Get shortcutNameEditText from the alert dialog.
2224 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
2226 // Create the bookmark shortcut based on formattedUrlString.
2227 Intent bookmarkShortcut = new Intent();
2228 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
2229 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
2231 // Place the bookmark shortcut on the home screen.
2232 Intent placeBookmarkShortcut = new Intent();
2233 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
2234 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
2235 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
2236 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
2237 sendBroadcast(placeBookmarkShortcut);
2241 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
2242 // Download the image if it has an HTTP or HTTPS URI.
2243 if (imageUrl.startsWith("http")) {
2244 // Get a handle for the system `DOWNLOAD_SERVICE`.
2245 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2247 // Parse `imageUrl`.
2248 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
2250 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2251 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2252 if (firstPartyCookiesEnabled) {
2253 // Get the cookies for `imageUrl`.
2254 String cookies = cookieManager.getCookie(imageUrl);
2256 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2257 downloadRequest.addRequestHeader("Cookie", cookies);
2260 // Get the file name from `dialogFragment`.
2261 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
2262 String imageName = downloadImageNameEditText.getText().toString();
2264 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2265 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2266 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2267 } else { // Only set the title using `imageName`.
2268 downloadRequest.setTitle(imageName);
2271 // Allow `MediaScanner` to index the download if it is a media file.
2272 downloadRequest.allowScanningByMediaScanner();
2274 // Add the URL as the description for the download.
2275 downloadRequest.setDescription(imageUrl);
2277 // Show the download notification after the download is completed.
2278 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2280 // Initiate the download.
2281 downloadManager.enqueue(downloadRequest);
2282 } else { // The image is not an HTTP or HTTPS URI.
2283 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2288 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2289 // Download the file if it has an HTTP or HTTPS URI.
2290 if (downloadUrl.startsWith("http")) {
2292 // Get a handle for the system `DOWNLOAD_SERVICE`.
2293 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2295 // Parse `downloadUrl`.
2296 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2298 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2299 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2300 if (firstPartyCookiesEnabled) {
2301 // Get the cookies for `downloadUrl`.
2302 String cookies = cookieManager.getCookie(downloadUrl);
2304 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2305 downloadRequest.addRequestHeader("Cookie", cookies);
2308 // Get the file name from `dialogFragment`.
2309 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2310 String fileName = downloadFileNameEditText.getText().toString();
2312 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2313 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2314 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2315 } else { // Only set the title using `fileName`.
2316 downloadRequest.setTitle(fileName);
2319 // Allow `MediaScanner` to index the download if it is a media file.
2320 downloadRequest.allowScanningByMediaScanner();
2322 // Add the URL as the description for the download.
2323 downloadRequest.setDescription(downloadUrl);
2325 // Show the download notification after the download is completed.
2326 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2328 // Initiate the download.
2329 downloadManager.enqueue(downloadRequest);
2330 } else { // The download is not an HTTP or HTTPS URI.
2331 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2336 public void onHttpAuthenticationCancel() {
2337 // Cancel the `HttpAuthHandler`.
2338 httpAuthHandler.cancel();
2342 public void onHttpAuthenticationProceed(AppCompatDialogFragment dialogFragment) {
2343 // Get handles for the `EditTexts`.
2344 EditText usernameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_username);
2345 EditText passwordEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.http_authentication_password);
2347 // Proceed with the HTTP authentication.
2348 httpAuthHandler.proceed(usernameEditText.getText().toString(), passwordEditText.getText().toString());
2351 public void viewSslCertificate(View view) {
2352 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2353 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2354 viewSslCertificateDialogFragment.show(getFragmentManager(), getString(R.string.view_ssl_certificate));
2358 public void onSslErrorCancel() {
2359 sslErrorHandler.cancel();
2363 public void onSslErrorProceed() {
2364 sslErrorHandler.proceed();
2368 public void onSslMismatchBack() {
2369 if (mainWebView.canGoBack()) { // There is a back page in the history.
2370 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2371 navigatingHistory = true;
2374 mainWebView.goBack();
2375 } else { // There are no pages to go back to.
2376 // Load a blank page
2382 public void onSslMismatchProceed() {
2383 // Do not check the pinned SSL certificate for this domain again until the domain changes.
2384 ignorePinnedSslCertificate = true;
2388 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2389 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2390 navigatingHistory = true;
2392 // Load the history entry.
2393 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2397 public void onClearHistory() {
2398 // Clear the history.
2399 mainWebView.clearHistory();
2402 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2404 public void onBackPressed() {
2405 if (drawerLayout.isDrawerVisible(GravityCompat.START)) { // The navigation drawer is open.
2406 // Close the navigation drawer.
2407 drawerLayout.closeDrawer(GravityCompat.START);
2408 } else if (drawerLayout.isDrawerVisible(GravityCompat.END)){ // The bookmarks drawer is open.
2409 if (currentBookmarksFolder.isEmpty()) { // The home folder is displayed.
2410 // close the bookmarks drawer.
2411 drawerLayout.closeDrawer(GravityCompat.END);
2412 } else { // A subfolder is displayed.
2413 // Place the former parent folder in `currentFolder`.
2414 currentBookmarksFolder = bookmarksDatabaseHelper.getParentFolder(currentBookmarksFolder);
2416 // Load the new folder.
2417 loadBookmarksFolder();
2420 } else if (mainWebView.canGoBack()) { // There is at least one item in the `WebView` history.
2421 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2422 navigatingHistory = true;
2425 mainWebView.goBack();
2426 } else { // There isn't anything to do in Privacy Browser.
2427 // Pass `onBackPressed()` to the system.
2428 super.onBackPressed();
2432 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2433 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2434 String unformattedUrlString = urlTextBox.getText().toString().trim();
2436 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2437 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2438 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2439 if (!unformattedUrlString.startsWith("http")) {
2440 unformattedUrlString = "http://" + unformattedUrlString;
2443 // Initialize `unformattedUrl`.
2444 URL unformattedUrl = null;
2446 // 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.
2448 unformattedUrl = new URL(unformattedUrlString);
2449 } catch (MalformedURLException e) {
2450 e.printStackTrace();
2453 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2454 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2455 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2456 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2457 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2458 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2461 Uri.Builder formattedUri = new Uri.Builder();
2462 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2464 // Decode `formattedUri` as a `String` in `UTF-8`.
2465 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2467 // Sanitize the search input and convert it to a search.
2468 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2470 // Add the base search URL.
2471 formattedUrlString = searchURL + encodedUrlString;
2474 loadUrl(formattedUrlString);
2476 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2477 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2481 private void loadUrl(String url) {
2482 // Apply any custom domain settings.
2483 applyDomainSettings(url);
2486 mainWebView.loadUrl(url, customHeaders);
2488 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2489 urlIsLoading = true;
2492 public void findPreviousOnPage(View view) {
2493 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2494 mainWebView.findNext(false);
2497 public void findNextOnPage(View view) {
2498 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2499 mainWebView.findNext(true);
2502 public void closeFindOnPage(View view) {
2503 // Delete the contents of `find_on_page_edittext`.
2504 findOnPageEditText.setText(null);
2506 // Clear the highlighted phrases.
2507 mainWebView.clearMatches();
2509 // Hide the Find on Page `RelativeLayout`.
2510 findOnPageLinearLayout.setVisibility(View.GONE);
2512 // Show the URL app bar.
2513 supportAppBar.setVisibility(View.VISIBLE);
2515 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2516 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2519 private void applyAppSettings() {
2520 // Get a handle for `sharedPreferences`. `this` references the current context.
2521 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2523 // Store the values from `sharedPreferences` in variables.
2524 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2525 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2526 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2527 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2528 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2529 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2530 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2531 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2532 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2533 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2534 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2535 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2536 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2537 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2538 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2540 // Set the homepage, search, and proxy options.
2541 if (proxyThroughOrbot) { // Set the Tor options.
2542 // Set `torHomepageString` as `homepage`.
2543 homepage = torHomepageString;
2545 // If formattedUrlString is null assign the homepage to it.
2546 if (formattedUrlString == null) {
2547 formattedUrlString = homepage;
2550 // Set the search URL.
2551 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2552 searchURL = torSearchCustomURLString;
2553 } else { // Use the string from the pre-built list.
2554 searchURL = torSearchString;
2557 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2558 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2560 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2562 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2564 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2567 // Display a message to the user if we are waiting on Orbot.
2568 if (!orbotStatus.equals("ON")) {
2569 // Set `waitingForOrbot`.
2570 waitingForOrbot = true;
2572 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2573 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2575 } else { // Set the non-Tor options.
2576 // Set `homepageString` as `homepage`.
2577 homepage = homepageString;
2579 // If formattedUrlString is null assign the homepage to it.
2580 if (formattedUrlString == null) {
2581 formattedUrlString = homepage;
2584 // Set the search URL.
2585 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2586 searchURL = searchCustomURLString;
2587 } else { // Use the string from the pre-built list.
2588 searchURL = searchString;
2591 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2592 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2594 // Set the default `appBar` background. `this` refers to the context.
2596 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2598 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2601 // Reset `waitingForOrbot.
2602 waitingForOrbot = false;
2605 // Set swipe to refresh.
2606 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2608 // Set Do Not Track status.
2609 if (doNotTrackEnabled) {
2610 customHeaders.put("DNT", "1");
2612 customHeaders.remove("DNT");
2615 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2616 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2617 if (hideSystemBarsOnFullscreen) { // Hide everything.
2618 // Remove the translucent navigation setting if it is currently flagged.
2619 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2621 // Remove the translucent status bar overlay.
2622 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2624 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2625 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2627 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2628 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2629 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2631 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2632 } else { // Hide everything except the status and navigation bars.
2633 // Add the translucent status flag if it is unset.
2634 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2636 if (translucentNavigationBarOnFullscreen) {
2637 // Set the navigation bar to be translucent.
2638 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2640 // Set the navigation bar to be black.
2641 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2644 } else { // Switch to normal viewing mode.
2645 // Reset `inFullScreenBrowsingMode` to `false`.
2646 inFullScreenBrowsingMode = false;
2648 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2649 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2653 // Show the `BannerAd` in the free flavor.
2654 if (BuildConfig.FLAVOR.contentEquals("free")) {
2655 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2656 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2658 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2659 adView = findViewById(R.id.adview);
2662 // Remove the translucent navigation bar flag if it is set.
2663 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2665 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2666 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2668 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2669 rootCoordinatorLayout.setSystemUiVisibility(0);
2671 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2672 rootCoordinatorLayout.setFitsSystemWindows(true);
2676 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2677 @SuppressWarnings("deprecation")
2678 private void applyDomainSettings(String url) {
2679 // Reset `navigatingHistory`.
2680 navigatingHistory = false;
2682 // Parse the URL into a URI.
2683 Uri uri = Uri.parse(url);
2685 // Extract the domain from `uri`.
2686 String hostName = uri.getHost();
2688 // Initialize `loadingNewDomainName`.
2689 boolean loadingNewDomainName;
2691 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2692 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2693 //noinspection SimplifiableIfStatement
2694 if ((hostName == null) || (currentDomainName == null)) {
2695 loadingNewDomainName = true;
2696 } else { // Determine if `hostName` equals `currentDomainName`.
2697 loadingNewDomainName = !hostName.equals(currentDomainName);
2700 // 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.
2701 if (loadingNewDomainName) {
2702 // Set the new `hostname` as the `currentDomainName`.
2703 currentDomainName = hostName;
2705 // Reset `ignorePinnedSslCertificate`.
2706 ignorePinnedSslCertificate = false;
2708 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2709 favoriteIconBitmap = favoriteIconDefaultBitmap;
2710 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2712 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2713 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2714 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2716 // Get a full cursor from `domainsDatabaseHelper`.
2717 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2719 // Initialize `domainSettingsSet`.
2720 Set<String> domainSettingsSet = new HashSet<>();
2722 // Get the domain name column index.
2723 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2725 // Populate `domainSettingsSet`.
2726 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2727 // Move `domainsCursor` to the current row.
2728 domainNameCursor.moveToPosition(i);
2730 // Store the domain name in `domainSettingsSet`.
2731 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2734 // Close `domainNameCursor.
2735 domainNameCursor.close();
2737 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2738 domainSettingsApplied = false;
2739 String domainNameInDatabase = null;
2741 // Check the hostname.
2742 if (domainSettingsSet.contains(hostName)) {
2743 domainSettingsApplied = true;
2744 domainNameInDatabase = hostName;
2747 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2748 if (hostName != null) {
2749 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2750 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2751 domainSettingsApplied = true;
2752 domainNameInDatabase = "*." + hostName;
2755 // Strip out the lowest subdomain of `host`.
2756 hostName = hostName.substring(hostName.indexOf(".") + 1);
2760 // Get a handle for the shared preference. `this` references the current context.
2761 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2763 // Store the general preference information.
2764 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2765 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2766 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2767 nightMode = sharedPreferences.getBoolean("night_mode", false);
2769 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2770 // Get a cursor for the current host and move it to the first position.
2771 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2772 currentHostDomainSettingsCursor.moveToFirst();
2774 // Get the settings from the cursor.
2775 domainSettingsDatabaseId = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper._ID)));
2776 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2777 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2778 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2779 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2780 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2781 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2782 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2783 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2784 int nightModeInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.NIGHT_MODE));
2785 pinnedDomainSslCertificate = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.PINNED_SSL_CERTIFICATE)) == 1);
2786 pinnedDomainSslIssuedToCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_COMMON_NAME));
2787 pinnedDomainSslIssuedToONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATION));
2788 pinnedDomainSslIssuedToUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_TO_ORGANIZATIONAL_UNIT));
2789 pinnedDomainSslIssuedByCNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_COMMON_NAME));
2790 pinnedDomainSslIssuedByONameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATION));
2791 pinnedDomainSslIssuedByUNameString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_ISSUED_BY_ORGANIZATIONAL_UNIT));
2793 // Set `nightMode` according to `nightModeInt`. If `nightModeInt` is `DomainsDatabaseHelper.NIGHT_MODE_SYSTEM_DEFAULT` the current setting from `sharedPreferences` will be used.
2794 switch (nightModeInt) {
2795 case DomainsDatabaseHelper.NIGHT_MODE_ENABLED:
2799 case DomainsDatabaseHelper.NIGHT_MODE_DISABLED:
2804 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
2806 javaScriptEnabled = true;
2809 // Set the pinned SSL certificate start date to `null` if the saved date `long` is 0.
2810 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)) == 0) {
2811 pinnedDomainSslStartDate = null;
2813 pinnedDomainSslStartDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_START_DATE)));
2816 // Set the pinned SSL certificate end date to `null` if the saved date `long` is 0.
2817 if (currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)) == 0) {
2818 pinnedDomainSslEndDate = null;
2820 pinnedDomainSslEndDate = new Date(currentHostDomainSettingsCursor.getLong(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.SSL_END_DATE)));
2823 // Close `currentHostDomainSettingsCursor`.
2824 currentHostDomainSettingsCursor.close();
2826 // Apply the domain settings.
2827 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2828 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2829 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2830 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2832 // Apply the font size.
2833 if (fontSize == 0) { // Apply the default font size.
2834 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2835 } else { // Apply the specified font size.
2836 mainWebView.getSettings().setTextZoom(fontSize);
2839 // Set third-party cookies status if API >= 21.
2840 if (Build.VERSION.SDK_INT >= 21) {
2841 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2844 // 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>
2845 if (!urlIsLoading) {
2846 switch (userAgentString) {
2847 case "System default user agent":
2848 // Set the user agent according to the system default.
2849 switch (defaultUserAgentString) {
2850 case "WebView default user agent":
2851 // Set the user agent to `""`, which uses the default value.
2852 mainWebView.getSettings().setUserAgentString("");
2855 case "Custom user agent":
2856 // Set the custom user agent.
2857 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2861 // Use the selected user agent.
2862 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2866 case "WebView default user agent":
2867 // Set the user agent to `""`, which uses the default value.
2868 mainWebView.getSettings().setUserAgentString("");
2872 // Use the selected user agent.
2873 mainWebView.getSettings().setUserAgentString(userAgentString);
2877 // 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.
2879 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
2881 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
2883 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2884 // Store the values from `sharedPreferences` in variables.
2885 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2886 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2887 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2888 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2889 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2891 // Set `javaScriptEnabled` to be `true` if `night_mode` is `true`.
2893 javaScriptEnabled = true;
2896 // Apply the default settings.
2897 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2898 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2899 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2900 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2901 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2903 // Reset the pinned SSL certificate information.
2904 domainSettingsDatabaseId = -1;
2905 pinnedDomainSslCertificate = false;
2906 pinnedDomainSslIssuedToCNameString = "";
2907 pinnedDomainSslIssuedToONameString = "";
2908 pinnedDomainSslIssuedToUNameString = "";
2909 pinnedDomainSslIssuedByCNameString = "";
2910 pinnedDomainSslIssuedByONameString = "";
2911 pinnedDomainSslIssuedByUNameString = "";
2912 pinnedDomainSslStartDate = null;
2913 pinnedDomainSslEndDate = null;
2915 // Set third-party cookies status if API >= 21.
2916 if (Build.VERSION.SDK_INT >= 21) {
2917 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2920 // 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>
2921 if (!urlIsLoading) {
2922 switch (defaultUserAgentString) {
2923 case "WebView default user agent":
2924 // Set the user agent to `""`, which uses the default value.
2925 mainWebView.getSettings().setUserAgentString("");
2928 case "Custom user agent":
2929 // Set the custom user agent.
2930 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2934 // Use the selected user agent.
2935 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2939 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2940 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
2943 // Close `domainsDatabaseHelper`.
2944 domainsDatabaseHelper.close();
2946 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2947 onTheFlyDisplayImagesSet = false;
2948 setDisplayWebpageImages();
2950 // Update the privacy icons, but only if `mainMenu` has already been populated.
2951 if (mainMenu != null) {
2952 updatePrivacyIcons(true);
2957 private void setDisplayWebpageImages() {
2958 if (!onTheFlyDisplayImagesSet) {
2959 if (domainSettingsApplied) { // Custom domain settings are applied.
2960 switch (displayWebpageImagesInt) {
2961 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2962 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2965 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2966 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2969 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2970 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2973 } else { // Default settings are applied.
2974 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2979 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2980 // Get handles for the icons.
2981 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2982 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2983 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2984 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2986 // Update `privacyIcon`.
2987 if (javaScriptEnabled) { // JavaScript is enabled.
2988 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2989 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2990 privacyIconMenuItem.setIcon(R.drawable.warning);
2991 } else { // All the dangerous features are disabled.
2992 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2995 // Update `firstPartyCookiesIcon`.
2996 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2997 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2998 } else { // First-party cookies are disabled.
3000 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
3002 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
3006 // Update `domStorageIcon`.
3007 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
3008 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
3009 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
3011 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
3013 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
3015 } else { // JavaScript is disabled, so DOM storage is ghosted.
3017 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
3019 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
3023 // Update `formDataIcon`.
3024 if (saveFormDataEnabled) { // Form data is enabled.
3025 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
3026 } else { // Form data is disabled.
3028 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
3030 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
3034 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
3035 if (runInvalidateOptionsMenu) {
3036 ActivityCompat.invalidateOptionsMenu(this);
3040 private void highlightUrlText() {
3041 String urlString = urlTextBox.getText().toString();
3043 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
3044 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3045 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
3046 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3049 // Get the index of the `/` immediately after the domain name.
3050 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
3052 // De-emphasize the text after the domain name.
3053 if (endOfDomainName > 0) {
3054 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
3058 private void loadBookmarksFolder() {
3059 // Update `bookmarksCursor` with the contents of the bookmarks database for the current folder.
3060 Cursor bookmarksCursor = bookmarksDatabaseHelper.getAllBookmarksCursorByDisplayOrder(currentBookmarksFolder);
3062 // Setup a `CursorAdapter`. `this` specifies the `Context`. `false` disables `autoRequery`.
3063 CursorAdapter bookmarksCursorAdapter = new CursorAdapter(this, bookmarksCursor, false) {
3065 public View newView(Context context, Cursor cursor, ViewGroup parent) {
3066 // Inflate the individual item layout. `false` does not attach it to the root.
3067 return getLayoutInflater().inflate(R.layout.bookmarks_drawer_item_linearlayout, parent, false);
3071 public void bindView(View view, Context context, Cursor cursor) {
3072 // Get handles for the views.
3073 ImageView bookmarkFavoriteIcon = (ImageView) view.findViewById(R.id.bookmark_favorite_icon);
3074 TextView bookmarkNameTextView = (TextView) view.findViewById(R.id.bookmark_name);
3076 // Get the favorite icon byte array from the `Cursor`.
3077 byte[] favoriteIconByteArray = cursor.getBlob(cursor.getColumnIndex(BookmarksDatabaseHelper.FAVORITE_ICON));
3079 // Convert the byte array to a `Bitmap` beginning at the first byte and ending at the last.
3080 Bitmap favoriteIconBitmap = BitmapFactory.decodeByteArray(favoriteIconByteArray, 0, favoriteIconByteArray.length);
3082 // Display the bitmap in `bookmarkFavoriteIcon`.
3083 bookmarkFavoriteIcon.setImageBitmap(favoriteIconBitmap);
3085 // Get the bookmark name from the cursor and display it in `bookmarkNameTextView`.
3086 String bookmarkNameString = cursor.getString(cursor.getColumnIndex(BookmarksDatabaseHelper.BOOKMARK_NAME));
3087 bookmarkNameTextView.setText(bookmarkNameString);
3089 // Make the font bold for folders.
3090 if (cursor.getInt(cursor.getColumnIndex(BookmarksDatabaseHelper.IS_FOLDER)) == 1) {
3091 bookmarkNameTextView.setTypeface(Typeface.DEFAULT_BOLD);
3092 } else { // Reset the font to default for normal bookmarks.
3093 bookmarkNameTextView.setTypeface(Typeface.DEFAULT);
3098 // Populate the `ListView` with the adapter.
3099 bookmarksListView.setAdapter(bookmarksCursorAdapter);
3101 // Set the bookmarks drawer title.
3102 if (currentBookmarksFolder.isEmpty()) {
3103 bookmarksTitleTextView.setText(R.string.bookmarks);
3105 bookmarksTitleTextView.setText(currentBookmarksFolder);