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.drawable.BitmapDrawable;
38 import android.graphics.drawable.Drawable;
39 import android.net.Uri;
40 import android.net.http.SslCertificate;
41 import android.net.http.SslError;
42 import android.os.Build;
43 import android.os.Bundle;
44 import android.preference.PreferenceManager;
45 import android.print.PrintDocumentAdapter;
46 import android.print.PrintManager;
47 import android.support.annotation.NonNull;
48 import android.support.design.widget.CoordinatorLayout;
49 import android.support.design.widget.NavigationView;
50 import android.support.design.widget.Snackbar;
51 import android.support.v4.app.ActivityCompat;
52 import android.support.v4.content.ContextCompat;
53 import android.support.v4.view.GravityCompat;
54 import android.support.v4.widget.DrawerLayout;
55 import android.support.v4.widget.SwipeRefreshLayout;
56 import android.support.v7.app.ActionBar;
57 import android.support.v7.app.ActionBarDrawerToggle;
58 import android.support.v7.app.AppCompatActivity;
59 import android.support.v7.app.AppCompatDialogFragment;
60 import android.support.v7.widget.Toolbar;
61 import android.text.Editable;
62 import android.text.Spanned;
63 import android.text.TextWatcher;
64 import android.text.style.ForegroundColorSpan;
65 import android.util.Patterns;
66 import android.view.ContextMenu;
67 import android.view.GestureDetector;
68 import android.view.KeyEvent;
69 import android.view.Menu;
70 import android.view.MenuItem;
71 import android.view.MotionEvent;
72 import android.view.View;
73 import android.view.WindowManager;
74 import android.view.inputmethod.InputMethodManager;
75 import android.webkit.CookieManager;
76 import android.webkit.DownloadListener;
77 import android.webkit.SslErrorHandler;
78 import android.webkit.WebBackForwardList;
79 import android.webkit.WebChromeClient;
80 import android.webkit.WebResourceResponse;
81 import android.webkit.WebStorage;
82 import android.webkit.WebView;
83 import android.webkit.WebViewClient;
84 import android.webkit.WebViewDatabase;
85 import android.widget.EditText;
86 import android.widget.FrameLayout;
87 import android.widget.ImageView;
88 import android.widget.LinearLayout;
89 import android.widget.ProgressBar;
90 import android.widget.RelativeLayout;
91 import android.widget.TextView;
93 import com.stoutner.privacybrowser.BannerAd;
94 import com.stoutner.privacybrowser.BuildConfig;
95 import com.stoutner.privacybrowser.R;
96 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcutDialog;
97 import com.stoutner.privacybrowser.dialogs.DownloadImageDialog;
98 import com.stoutner.privacybrowser.dialogs.UrlHistoryDialog;
99 import com.stoutner.privacybrowser.dialogs.ViewSslCertificateDialog;
100 import com.stoutner.privacybrowser.helpers.DomainsDatabaseHelper;
101 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
102 import com.stoutner.privacybrowser.dialogs.DownloadFileDialog;
103 import com.stoutner.privacybrowser.dialogs.SslCertificateErrorDialog;
105 import java.io.BufferedReader;
106 import java.io.ByteArrayInputStream;
108 import java.io.IOException;
109 import java.io.InputStreamReader;
110 import java.io.UnsupportedEncodingException;
111 import java.net.MalformedURLException;
113 import java.net.URLDecoder;
114 import java.net.URLEncoder;
115 import java.util.HashMap;
116 import java.util.HashSet;
117 import java.util.Map;
118 import java.util.Set;
120 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
121 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcutDialog.CreateHomeScreenSchortcutListener,
122 SslCertificateErrorDialog.SslCertificateErrorListener, DownloadFileDialog.DownloadFileListener, DownloadImageDialog.DownloadImageListener, UrlHistoryDialog.UrlHistoryListener {
124 // `darkTheme` is public static so it can be accessed from `AboutActivity`, `GuideActivity`, `AddDomainDialog`, `SettingsActivity`, `DomainsActivity`, `DomainsListFragment`, `BookmarksActivity`, `BookmarksDatabaseViewActivity`,
125 // `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `DownloadFileDialog`, `DownloadImageDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `MoveToFolderDialog`, `SslCertificateErrorDialog`, `UrlHistoryDialog`, `ViewSslCertificateDialog`,
126 // `CreateHomeScreenShortcutDialog`, and `OrbotProxyHelper`. It is also used in `onCreate()`, `applyAppSettings()`, `applyDomainSettings()`, and `updatePrivacyIcons()`.
127 public static boolean darkTheme;
129 // `favoriteIconBitmap` is public static so it can be accessed from `CreateHomeScreenShortcutDialog`, `BookmarksActivity`, `CreateBookmarkDialog`, `CreateBookmarkFolderDialog`, `EditBookmarkDialog`, `EditBookmarkFolderDialog`, `ViewSslCertificateDialog`.
130 // It is also used in `onCreate()`, `onCreateHomeScreenShortcutCreate()`, and `applyDomainSettings`.
131 public static Bitmap favoriteIconBitmap;
133 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`, `CreateBookmarkDialog`, and `AddDomainDialog`.
134 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
135 public static String formattedUrlString;
137 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificateDialog`. It is also used in `onCreate()`.
138 public static SslCertificate sslCertificate;
140 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
141 public static String orbotStatus;
143 // `webViewTitle` is public static so it can be accessed from `CreateBookmarkDialog` and `CreateHomeScreenShortcutDialog`. It is also used in `onCreate()`.
144 public static String webViewTitle;
146 // `displayWebpageImagesBoolean` is public static so it can be accessed from `DomainSettingsFragment`. It is also used in `applyAppSettings()` and `applyDomainSettings()`.
147 public static boolean displayWebpageImagesBoolean;
149 // `reloadOnRestartBoolean` is public static so it can be accessed from `SettingsFragment`. It is also used in `onRestart()`
150 public static boolean reloadOnRestartBoolean;
153 // `appBar` is used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applyAppSettings()`.
154 private ActionBar appBar;
156 // `navigatingHistory` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
157 private boolean navigatingHistory;
159 // `favoriteIconDefaultBitmap` is used in `onCreate()` and `applyDomainSettings`.
160 private Bitmap favoriteIconDefaultBitmap;
162 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
163 private DrawerLayout drawerLayout;
165 // `rootCoordinatorLayout` is used in `onCreate()` and `applyAppSettings()`.
166 private CoordinatorLayout rootCoordinatorLayout;
168 // `mainWebView` is used in `onCreate()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, `loadUrlFromTextBox()`
169 // and `setDisplayWebpageImages()`.
170 private WebView mainWebView;
172 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
173 private FrameLayout fullScreenVideoFrameLayout;
175 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
176 private SwipeRefreshLayout swipeRefreshLayout;
178 // `urlAppBarRelativeLayout` is used in `onCreate()` and `applyDomainSettings()`.
179 private RelativeLayout urlAppBarRelativeLayout;
181 // `favoriteIconImageView` is used in `onCreate()` and `applyDomainSettings()`
182 private ImageView favoriteIconImageView;
184 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `loadUrlFromTextBox()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
185 private CookieManager cookieManager;
187 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrl()`.
188 private final Map<String, String> customHeaders = new HashMap<>();
190 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applyAppSettings()`.
191 // It is `Boolean` instead of `boolean` because `applyAppSettings()` needs to know if it is `null`.
192 private Boolean javaScriptEnabled;
194 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applyAppSettings()`.
195 private boolean firstPartyCookiesEnabled;
197 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
198 private boolean thirdPartyCookiesEnabled;
200 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
201 private boolean domStorageEnabled;
203 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
204 private boolean saveFormDataEnabled;
206 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applyAppSettings()`.
207 private boolean swipeToRefreshEnabled;
209 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applyAppSettings()`.
210 private String homepage;
212 // `searchURL` is used in `loadURLFromTextBox()` and `applyAppSettings()`.
213 private String searchURL;
215 // `adBlockerEnabled` is used in `onCreate()` and `applyAppSettings()`.
216 private boolean adBlockerEnabled;
218 // `privacyBrowserRuntime` is used in `onCreate()`, `onOptionsItemSelected()`, and `applyAppSettings()`.
219 private Runtime privacyBrowserRuntime;
221 // `incognitoModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
222 private boolean incognitoModeEnabled;
224 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applyAppSettings()`.
225 private boolean fullScreenBrowsingModeEnabled;
227 // `inFullScreenBrowsingMode` is used in `onCreate()`, `onConfigurationChanged()`, and `applyAppSettings()`.
228 private boolean inFullScreenBrowsingMode;
230 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
231 private boolean hideSystemBarsOnFullscreen;
233 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applyAppSettings()`.
234 private boolean translucentNavigationBarOnFullscreen;
236 // `currentDomainName` is used in `onCreate()`, `onNavigationItemSelected()`, and `applyDomainSettings()`.
237 private String currentDomainName;
239 // `waitingForOrbot` is used in `onCreate()` and `applyAppSettings()`.
240 private boolean waitingForOrbot;
242 // `domainSettingsApplied` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
243 private boolean domainSettingsApplied;
245 // `displayWebpageImagesInt` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
246 private int displayWebpageImagesInt;
248 // `onTheFlyDisplayImagesSet` is used in `applyDomainSettings()` and `setDisplayWebpageImages()`.
249 private boolean onTheFlyDisplayImagesSet;
251 // `waitingForOrbotData` is used in `onCreate()` and `applyAppSettings()`.
252 private String waitingForOrbotHTMLString;
254 // `privateDataDirectoryString` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
255 private String privateDataDirectoryString;
257 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
258 private LinearLayout findOnPageLinearLayout;
260 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
261 private EditText findOnPageEditText;
263 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
264 private Menu mainMenu;
266 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
267 private ActionBarDrawerToggle drawerToggle;
269 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
270 private Toolbar supportAppBar;
272 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, `loadUrl()`, and `highlightUrlText()`.
273 private EditText urlTextBox;
275 // `redColorSpan` is used in `onCreate()` and `highlightUrlText()`.
276 private ForegroundColorSpan redColorSpan;
278 // `initialGrayColorSpan` is sued in `onCreate()` and `highlightUrlText()`.
279 private ForegroundColorSpan initialGrayColorSpan;
281 // `finalGrayColorSpam` is used in `onCreate()` and `highlightUrlText()`.
282 private ForegroundColorSpan finalGrayColorSpan;
284 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
287 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
288 private SslErrorHandler sslErrorHandler;
290 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
291 private InputMethodManager inputMethodManager;
293 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
294 private RelativeLayout mainWebViewRelativeLayout;
296 // `urlIsLoading` is used in `onCreate()`, `loadUrl()`, and `applyDomainSettings()`.
297 private boolean urlIsLoading;
300 // 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.
301 @SuppressLint("SetJavaScriptEnabled")
302 // Remove Android Studio's warning about deprecations. We have to use the deprecated `getColor()` until API >= 23.
303 @SuppressWarnings("deprecation")
304 protected void onCreate(Bundle savedInstanceState) {
305 // Get a handle for `sharedPreferences`. `this` references the current context.
306 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
308 // Get the theme preference.
309 darkTheme = sharedPreferences.getBoolean("dark_theme", false);
311 // Set the activity theme.
313 setTheme(R.style.PrivacyBrowserDark);
315 setTheme(R.style.PrivacyBrowserLight);
318 // Run the default commands.
319 super.onCreate(savedInstanceState);
321 // Set the content view.
322 setContentView(R.layout.main_drawerlayout);
324 // Get a handle for `inputMethodManager`.
325 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
327 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
328 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
329 setSupportActionBar(supportAppBar);
330 appBar = getSupportActionBar();
332 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
333 assert appBar != null;
335 // Add the custom `url_app_bar` layout, which shows the favorite icon and the URL text bar.
336 appBar.setCustomView(R.layout.url_app_bar);
337 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
339 // Initialize the `ForegroundColorSpans` and `StyleSpan` for highlighting `urlTextBox`. We have to use the deprecated `getColor()` until API >= 23.
340 redColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.red_a700));
341 initialGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
342 finalGrayColorSpan = new ForegroundColorSpan(getResources().getColor(R.color.gray_500));
344 // Get a handle for `urlTextBox`.
345 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.url_edittext);
347 // Remove the formatting from `urlTextBar` when the user is editing the text.
348 urlTextBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
350 public void onFocusChange(View v, boolean hasFocus) {
351 if (hasFocus) { // The user is editing `urlTextBox`.
352 // Remove the highlighting.
353 urlTextBox.getText().removeSpan(redColorSpan);
354 urlTextBox.getText().removeSpan(initialGrayColorSpan);
355 urlTextBox.getText().removeSpan(finalGrayColorSpan);
356 } else { // The user has stopped editing `urlTextBox`.
357 // Reapply the highlighting.
363 // Set the `Go` button on the keyboard to load the URL in `urlTextBox`.
364 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
366 public boolean onKey(View v, int keyCode, KeyEvent event) {
367 // If the event is a key-down event on the `enter` button, load the URL.
368 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
369 // Load the URL into the mainWebView and consume the event.
371 loadUrlFromTextBox();
372 } catch (UnsupportedEncodingException e) {
375 // If the enter key was pressed, consume the event.
378 // If any other key was pressed, do not consume the event.
384 // Set `waitingForOrbotHTMLString`.
385 waitingForOrbotHTMLString = "<html><body><br/><center><h1>" + getString(R.string.waiting_for_orbot) + "</h1></center></body></html>";
387 // Initialize `currentDomainName`, `orbotStatus`, and `waitingForOrbot`.
388 currentDomainName = "";
389 orbotStatus = "unknown";
390 waitingForOrbot = false;
392 // Create an Orbot status `BroadcastReceiver`.
393 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
395 public void onReceive(Context context, Intent intent) {
396 // Store the content of the status message in `orbotStatus`.
397 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
399 // If we are waiting on Orbot, load the website now that Orbot is connected.
400 if (orbotStatus.equals("ON") && waitingForOrbot) {
401 // Reset `waitingForOrbot`.
402 waitingForOrbot = false;
404 // Load `formattedUrlString
405 loadUrl(formattedUrlString);
410 // Register `orbotStatusBroadcastReceiver` on `this` context.
411 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
413 // Get handles for views that need to be accessed.
414 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
415 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
416 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
417 mainWebView = (WebView) findViewById(R.id.main_webview);
418 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
419 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
420 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
421 urlAppBarRelativeLayout = (RelativeLayout) findViewById(R.id.url_app_bar_relativelayout);
422 favoriteIconImageView = (ImageView) findViewById(R.id.favorite_icon);
424 // Create a double-tap listener to toggle full-screen mode.
425 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
426 // Override `onDoubleTap()`. All other events are handled using the default settings.
428 public boolean onDoubleTap(MotionEvent event) {
429 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
430 // Toggle `inFullScreenBrowsingMode`.
431 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
433 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
434 // Hide the `appBar`.
437 // Hide the `BannerAd` in the free flavor.
438 if (BuildConfig.FLAVOR.contentEquals("free")) {
439 BannerAd.hideAd(adView);
442 // Modify the system bars.
443 if (hideSystemBarsOnFullscreen) { // Hide everything.
444 // Remove the translucent overlays.
445 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
447 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
448 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
450 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
451 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
452 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
454 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
456 // Set `rootCoordinatorLayout` to fill the whole screen.
457 rootCoordinatorLayout.setFitsSystemWindows(false);
458 } else { // Hide everything except the status and navigation bars.
459 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
460 rootCoordinatorLayout.setFitsSystemWindows(false);
462 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.
463 // Set the navigation bar to be translucent.
464 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
467 } else { // Switch to normal viewing mode.
468 // Show the `appBar`.
471 // Show the `BannerAd` in the free flavor.
472 if (BuildConfig.FLAVOR.contentEquals("free")) {
473 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
474 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
476 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
477 adView = findViewById(R.id.adview);
480 // Remove the translucent navigation bar flag if it is set.
481 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
483 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
484 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
486 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
487 rootCoordinatorLayout.setSystemUiVisibility(0);
489 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
490 rootCoordinatorLayout.setFitsSystemWindows(true);
493 // Consume the double-tap.
495 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
501 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
502 mainWebView.setOnTouchListener(new View.OnTouchListener() {
504 public boolean onTouch(View v, MotionEvent event) {
505 // Send the `event` to `gestureDetector`.
506 return gestureDetector.onTouchEvent(event);
510 // Update `findOnPageCountTextView`.
511 mainWebView.setFindListener(new WebView.FindListener() {
512 // Get a handle for `findOnPageCountTextView`.
513 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
516 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
517 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
518 // Set `findOnPageCountTextView` to `0/0`.
519 findOnPageCountTextView.setText(R.string.zero_of_zero);
520 } else if (isDoneCounting) { // There are matches.
521 // `activeMatchOrdinal` is zero-based.
522 int activeMatch = activeMatchOrdinal + 1;
524 // Set `findOnPageCountTextView`.
525 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
530 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
531 findOnPageEditText.addTextChangedListener(new TextWatcher() {
533 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
538 public void onTextChanged(CharSequence s, int start, int before, int count) {
543 public void afterTextChanged(Editable s) {
544 // Search for the text in `mainWebView`.
545 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
549 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
550 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
552 public boolean onKey(View v, int keyCode, KeyEvent event) {
553 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
554 // Hide the soft keyboard. `0` indicates no additional flags.
555 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
557 // Consume the event.
559 } else { // A different key was pressed.
560 // Do not consume the event.
566 // Implement swipe to refresh
567 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refreshlayout);
568 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
569 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
571 public void onRefresh() {
572 mainWebView.reload();
576 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
577 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
579 // Listen for touches on the navigation menu.
580 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
581 navigationView.setNavigationItemSelectedListener(this);
583 // 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.
584 final Menu navigationMenu = navigationView.getMenu();
585 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
586 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
587 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
589 // The `DrawerListener` allows us to update the Navigation Menu.
590 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
592 public void onDrawerSlide(View drawerView, float slideOffset) {
596 public void onDrawerOpened(View drawerView) {
600 public void onDrawerClosed(View drawerView) {
604 public void onDrawerStateChanged(int newState) {
605 if ((newState == DrawerLayout.STATE_SETTLING) || (newState == DrawerLayout.STATE_DRAGGING)) { // The drawer is opening or closing.
606 // Update the `Back`, `Forward`, and `History` menu items.
607 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
608 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
609 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
611 // Hide the keyboard (if displayed) so we can see the navigation menu. `0` indicates no additional flags.
612 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
614 // Clear the focus from `urlTextBox` if it has it.
615 urlTextBox.clearFocus();
620 // drawerToggle creates the hamburger icon at the start of the AppBar.
621 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
623 // Initialize `adServerSet`.
624 final Set<String> adServersSet = new HashSet<>();
626 // Load the list of ad servers into memory.
628 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
629 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
631 // Create a string for storing each ad server.
634 // Populate `adServersSet`.
635 while ((adServer = bufferedReader.readLine()) != null) {
636 adServersSet.add(adServer);
639 // Close `bufferedReader`.
640 bufferedReader.close();
641 } catch (IOException ioException) {
642 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
645 mainWebView.setWebViewClient(new WebViewClient() {
646 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
647 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
648 @SuppressWarnings("deprecation")
650 public boolean shouldOverrideUrlLoading(WebView view, String url) {
651 if (url.startsWith("mailto:")) { // Load the URL in an external email program because it begins with `mailto:`.
652 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
653 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
655 // Parse the url and set it as the data for the `Intent`.
656 emailIntent.setData(Uri.parse(url));
658 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
659 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
662 startActivity(emailIntent);
664 // Returning `true` indicates the application is handling the URL.
666 } else { // Load the URL in Privacy Browser.
667 // Apply the domain settings for the new URL.
668 applyDomainSettings(url);
670 // Returning `false` causes the current `WebView` to handle the URL and prevents it from adding redirects to the history list.
675 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
676 @SuppressWarnings("deprecation")
678 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
679 if (adBlockerEnabled) { // Block ads.
680 // Extract the host from `url`.
681 Uri requestUri = Uri.parse(url);
682 String requestHost = requestUri.getHost();
684 // Initialize a variable to track if this is an ad server.
685 boolean requestHostIsAdServer = false;
687 // Check all the subdomains of `requestHost` if it is not `null` against the ad server database.
688 if (requestHost != null) {
689 while (requestHost.contains(".") && !requestHostIsAdServer) { // Stop checking if we run out of `.` or if we already know that `requestHostIsAdServer` is `true`.
690 if (adServersSet.contains(requestHost)) {
691 requestHostIsAdServer = true;
694 // Strip out the lowest subdomain of `requestHost`.
695 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
699 if (requestHostIsAdServer) { // It is an ad server.
700 // Return an empty `WebResourceResponse`.
701 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
702 } else { // It is not an ad server.
703 // `return null` loads the requested resource.
706 } else { // Ad blocking is disabled.
707 // `return null` loads the requested resource.
712 // Update the URL in urlTextBox when the page starts to load.
714 public void onPageStarted(WebView view, String url, Bitmap favicon) {
715 // Check to see if we are waiting on Orbot.
716 if (!waitingForOrbot) { // We are not waiting on Orbot, so we need to process the URL.
717 // 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.
718 formattedUrlString = url;
720 // Display the formatted URL text.
721 urlTextBox.setText(formattedUrlString);
723 // Apply text highlighting to `urlTextBox`.
726 // Apply any custom domain settings if the URL was loaded by navigating history.
727 if (navigatingHistory) {
728 applyDomainSettings(url);
731 // 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.
736 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
738 public void onPageFinished(WebView view, String url) {
739 // Reset `urlIsLoading`, which is used to prevent reloads on redirect if the user agent changes.
740 urlIsLoading = false;
742 // Clear the cache and history if Incognito Mode is enabled.
743 if (incognitoModeEnabled) {
744 // Clear the cache. `true` includes disk files.
745 mainWebView.clearCache(true);
747 // Clear the back/forward history.
748 mainWebView.clearHistory();
750 // Manually delete cache folders.
752 // Delete the main `cache` folder.
753 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
755 // 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`.
756 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
757 } catch (IOException e) {
758 // Do nothing if an error is thrown.
762 // Update `urlTextBox` and apply domain settings if not waiting on Orbot.
763 if (!waitingForOrbot) {
764 // Check to see if `WebView` has set `url` to be `about:blank`.
765 if (url.equals("about:blank")) { // `WebView` is blank, so `formattedUrlString` should be `""` and `urlTextBox` should display a hint.
766 // Set `formattedUrlString` to `""`.
767 formattedUrlString = "";
769 urlTextBox.setText(formattedUrlString);
771 // Request focus for `urlTextBox`.
772 urlTextBox.requestFocus();
774 // Display the keyboard.
775 inputMethodManager.showSoftInput(urlTextBox, 0);
777 // Apply the domain settings. This clears any settings from the previous domain.
778 applyDomainSettings(formattedUrlString);
779 } else { // `WebView` has loaded a webpage.
780 // Set `formattedUrlString`.
781 formattedUrlString = url;
783 // Only update `urlTextBox` if the user is not typing in it.
784 if (!urlTextBox.hasFocus()) {
785 // Display the formatted URL text.
786 urlTextBox.setText(formattedUrlString);
788 // Apply text highlighting to `urlTextBox`.
793 // Store the SSL certificate so it can be accessed from `ViewSslCertificateDialog`.
794 sslCertificate = mainWebView.getCertificate();
798 // Handle SSL Certificate errors.
800 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
801 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
802 sslErrorHandler = handler;
804 // Display the SSL error `AlertDialog`.
805 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateErrorDialog.displayDialog(error);
806 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
810 // Get a handle for the progress bar.
811 final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
813 mainWebView.setWebChromeClient(new WebChromeClient() {
814 // Update the progress bar when a page is loading.
816 public void onProgressChanged(WebView view, int progress) {
817 progressBar.setProgress(progress);
818 if (progress < 100) {
819 progressBar.setVisibility(View.VISIBLE);
821 progressBar.setVisibility(View.GONE);
823 //Stop the `SwipeToRefresh` indicator if it is running
824 swipeRefreshLayout.setRefreshing(false);
828 // Set the favorite icon when it changes.
830 public void onReceivedIcon(WebView view, Bitmap icon) {
831 // Only update the favorite icon if the website has finished loading.
832 if (progressBar.getVisibility() == View.GONE) {
833 // Save a copy of the favorite icon.
834 favoriteIconBitmap = icon;
836 // Place the favorite icon in the appBar.
837 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
841 // Save a copy of the title when it changes.
843 public void onReceivedTitle(WebView view, String title) {
844 // Save a copy of the title.
845 webViewTitle = title;
848 // Enter full screen video
850 public void onShowCustomView(View view, CustomViewCallback callback) {
851 // Pause the ad if this is the free flavor.
852 if (BuildConfig.FLAVOR.contentEquals("free")) {
853 BannerAd.pauseAd(adView);
856 // Remove the translucent overlays.
857 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
859 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
860 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
862 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
863 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
864 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
866 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
868 // Set `rootCoordinatorLayout` to fill the entire screen.
869 rootCoordinatorLayout.setFitsSystemWindows(false);
871 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
872 fullScreenVideoFrameLayout.addView(view);
873 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
876 // Exit full screen video
877 public void onHideCustomView() {
878 // Hide `fullScreenVideoFrameLayout`.
879 fullScreenVideoFrameLayout.removeAllViews();
880 fullScreenVideoFrameLayout.setVisibility(View.GONE);
882 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
883 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
885 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
886 rootCoordinatorLayout.setFitsSystemWindows(true);
888 // Show the ad if this is the free flavor.
889 if (BuildConfig.FLAVOR.contentEquals("free")) {
890 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
891 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
893 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
894 adView = findViewById(R.id.adview);
899 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
900 registerForContextMenu(mainWebView);
902 // Allow the downloading of files.
903 mainWebView.setDownloadListener(new DownloadListener() {
905 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
906 // Show the `DownloadFileDialog` `AlertDialog` and name this instance `@string/download`.
907 AppCompatDialogFragment downloadFileDialogFragment = DownloadFileDialog.fromUrl(url, contentDisposition, contentLength);
908 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
912 // Allow pinch to zoom.
913 mainWebView.getSettings().setBuiltInZoomControls(true);
915 // Hide zoom controls.
916 mainWebView.getSettings().setDisplayZoomControls(false);
918 // Set `mainWebView` to use a wide viewport. Otherwise, some web pages will be scrunched and some content will render outside the screen.
919 mainWebView.getSettings().setUseWideViewPort(true);
921 // Set `mainWebView` to load in overview mode (zoomed out to the maximum width).
922 mainWebView.getSettings().setLoadWithOverviewMode(true);
924 // Initialize cookieManager.
925 cookieManager = CookieManager.getInstance();
927 // 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).
928 customHeaders.put("X-Requested-With", "");
930 // 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.
931 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
933 // Get the intent that started the app.
934 final Intent launchingIntent = getIntent();
936 // Extract the launching intent data as `launchingIntentUriData`.
937 final Uri launchingIntentUriData = launchingIntent.getData();
939 // Convert the launching intent URI data (if it exists) to a string and store it in `formattedUrlString`.
940 if (launchingIntentUriData != null) {
941 formattedUrlString = launchingIntentUriData.toString();
944 // Get a handle for the `Runtime`.
945 privacyBrowserRuntime = Runtime.getRuntime();
947 // Store the application's private data directory.
948 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`.
950 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
951 inFullScreenBrowsingMode = false;
953 // Initialize AdView for the free flavor.
954 adView = findViewById(R.id.adview);
956 // Initialize the privacy settings variables.
957 javaScriptEnabled = false;
958 firstPartyCookiesEnabled = false;
959 thirdPartyCookiesEnabled = false;
960 domStorageEnabled = false;
961 saveFormDataEnabled = false;
963 // Initialize `webViewTitle`.
964 webViewTitle = getString(R.string.no_title);
966 // Initialize `favoriteIconBitmap`. We have to use `ContextCompat` until API >= 21.
967 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
968 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
969 favoriteIconDefaultBitmap = favoriteIconBitmapDrawable.getBitmap();
971 // If the favorite icon is null, load the default.
972 if (favoriteIconBitmap == null) {
973 favoriteIconBitmap = favoriteIconDefaultBitmap;
976 // Apply the app settings from the shared preferences.
979 // Load `formattedUrlString` if we are not waiting for Orbot to connect.
980 if (!waitingForOrbot) {
981 loadUrl(formattedUrlString);
986 protected void onNewIntent(Intent intent) {
987 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
990 if (intent.getData() != null) {
991 // Get the intent data and convert it to a string.
992 final Uri intentUriData = intent.getData();
993 formattedUrlString = intentUriData.toString();
996 // Close the navigation drawer if it is open.
997 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
998 drawerLayout.closeDrawer(GravityCompat.START);
1001 // Load the website.
1002 loadUrl(formattedUrlString);
1004 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
1005 mainWebView.requestFocus();
1009 public void onRestart() {
1012 // Apply the app settings, which may have been changed in `SettingsActivity`.
1015 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1016 updatePrivacyIcons(true);
1018 // Set the display webpage images mode.
1019 setDisplayWebpageImages();
1021 // Reload the webpage if displaying of images has been disabled in `SettingsFragment`.
1022 if (reloadOnRestartBoolean) {
1023 // Reload `mainWebView`.
1024 mainWebView.reload();
1026 // Reset `reloadOnRestartBoolean`.
1027 reloadOnRestartBoolean = false;
1031 // `onResume()` runs after `onStart()`, which runs after `onCreate()` and `onRestart()`.
1033 public void onResume() {
1036 // Resume JavaScript (if enabled).
1037 mainWebView.resumeTimers();
1039 // Resume `mainWebView`.
1040 mainWebView.onResume();
1042 // Resume the adView for the free flavor.
1043 if (BuildConfig.FLAVOR.contentEquals("free")) {
1044 BannerAd.resumeAd(adView);
1049 public void onPause() {
1050 // Pause `mainWebView`.
1051 mainWebView.onPause();
1053 // Stop all JavaScript.
1054 mainWebView.pauseTimers();
1056 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1057 if (BuildConfig.FLAVOR.contentEquals("free")) {
1058 BannerAd.pauseAd(adView);
1065 public boolean onCreateOptionsMenu(Menu menu) {
1066 // Inflate the menu; this adds items to the action bar if it is present.
1067 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
1069 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
1072 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
1073 updatePrivacyIcons(false);
1075 // Get handles for the menu items.
1076 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1077 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1078 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1079 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1081 // Only display third-party cookies if SDK >= 21
1082 toggleThirdPartyCookiesMenuItem.setVisible(Build.VERSION.SDK_INT >= 21);
1084 // Get the shared preference values. `this` references the current context.
1085 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1087 // Set the status of the additional app bar icons. The default is `false`.
1088 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
1089 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1090 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1091 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
1092 } else { //Do not display the additional icons.
1093 toggleFirstPartyCookiesMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1094 toggleDomStorageMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1095 toggleSaveFormDataMenuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
1102 public boolean onPrepareOptionsMenu(Menu menu) {
1103 // Get handles for the menu items.
1104 MenuItem toggleFirstPartyCookiesMenuItem = menu.findItem(R.id.toggle_first_party_cookies);
1105 MenuItem toggleThirdPartyCookiesMenuItem = menu.findItem(R.id.toggle_third_party_cookies);
1106 MenuItem toggleDomStorageMenuItem = menu.findItem(R.id.toggle_dom_storage);
1107 MenuItem toggleSaveFormDataMenuItem = menu.findItem(R.id.toggle_save_form_data);
1108 MenuItem clearCookiesMenuItem = menu.findItem(R.id.clear_cookies);
1109 MenuItem clearDOMStorageMenuItem = menu.findItem(R.id.clear_dom_storage);
1110 MenuItem clearFormDataMenuItem = menu.findItem(R.id.clear_form_data);
1111 MenuItem fontSizeMenuItem = menu.findItem(R.id.font_size);
1112 MenuItem displayImagesMenuItem = menu.findItem(R.id.display_images);
1113 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
1115 // Set the status of the menu item checkboxes.
1116 toggleFirstPartyCookiesMenuItem.setChecked(firstPartyCookiesEnabled);
1117 toggleThirdPartyCookiesMenuItem.setChecked(thirdPartyCookiesEnabled);
1118 toggleDomStorageMenuItem.setChecked(domStorageEnabled);
1119 toggleSaveFormDataMenuItem.setChecked(saveFormDataEnabled);
1120 displayImagesMenuItem.setChecked(mainWebView.getSettings().getLoadsImagesAutomatically());
1122 // Enable third-party cookies if first-party cookies are enabled.
1123 toggleThirdPartyCookiesMenuItem.setEnabled(firstPartyCookiesEnabled);
1125 // Enable `DOM Storage` if JavaScript is enabled.
1126 toggleDomStorageMenuItem.setEnabled(javaScriptEnabled);
1128 // Enable `Clear Cookies` if there are any.
1129 clearCookiesMenuItem.setEnabled(cookieManager.hasCookies());
1131 // Get a count of the number of files in the `Local Storage` directory.
1132 File localStorageDirectory = new File (privateDataDirectoryString + "/app_webview/Local Storage/");
1133 int localStorageDirectoryNumberOfFiles = 0;
1134 if (localStorageDirectory.exists()) {
1135 localStorageDirectoryNumberOfFiles = localStorageDirectory.list().length;
1138 // Get a count of the number of files in the `IndexedDB` directory.
1139 File indexedDBDirectory = new File (privateDataDirectoryString + "/app_webview/IndexedDB");
1140 int indexedDBDirectoryNumberOfFiles = 0;
1141 if (indexedDBDirectory.exists()) {
1142 indexedDBDirectoryNumberOfFiles = indexedDBDirectory.list().length;
1145 // Enable `Clear DOM Storage` if there is any.
1146 clearDOMStorageMenuItem.setEnabled(localStorageDirectoryNumberOfFiles > 0 || indexedDBDirectoryNumberOfFiles > 0);
1148 // Enable `Clear Form Data` is there is any.
1149 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1150 clearFormDataMenuItem.setEnabled(mainWebViewDatabase.hasFormData());
1152 // Initialize font size variables.
1153 int fontSize = mainWebView.getSettings().getTextZoom();
1154 String fontSizeTitle;
1155 MenuItem selectedFontSizeMenuItem;
1157 // Prepare the font size title and current size menu item.
1160 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.twenty_five_percent);
1161 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_twenty_five_percent);
1165 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
1166 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_fifty_percent);
1170 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
1171 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_seventy_five_percent);
1175 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1176 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1180 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
1181 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_twenty_five_percent);
1185 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
1186 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_fifty_percent);
1190 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
1191 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_seventy_five_percent);
1195 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
1196 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_two_hundred_percent);
1200 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
1201 selectedFontSizeMenuItem = menu.findItem(R.id.font_size_one_hundred_percent);
1205 // Set the font size title and select the current size menu item.
1206 fontSizeMenuItem.setTitle(fontSizeTitle);
1207 selectedFontSizeMenuItem.setChecked(true);
1209 // Only show `Refresh` if `swipeToRefresh` is disabled.
1210 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
1212 // Run all the other default commands.
1213 super.onPrepareOptionsMenu(menu);
1215 // `return true` displays the menu.
1220 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
1221 @SuppressLint("SetJavaScriptEnabled")
1222 // removeAllCookies is deprecated, but it is required for API < 21.
1223 @SuppressWarnings("deprecation")
1224 public boolean onOptionsItemSelected(MenuItem menuItem) {
1225 int menuItemId = menuItem.getItemId();
1227 // Set the commands that relate to the menu entries.
1228 switch (menuItemId) {
1229 case R.id.toggle_javascript:
1230 // Switch the status of javaScriptEnabled.
1231 javaScriptEnabled = !javaScriptEnabled;
1233 // Apply the new JavaScript status.
1234 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1236 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1237 updatePrivacyIcons(true);
1239 // Display a `Snackbar`.
1240 if (javaScriptEnabled) { // JavaScrip is enabled.
1241 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
1242 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
1243 Snackbar.make(findViewById(R.id.main_webview), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
1244 } else { // Privacy mode.
1245 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1248 // Reload the WebView.
1249 mainWebView.reload();
1252 case R.id.toggle_first_party_cookies:
1253 // Switch the status of firstPartyCookiesEnabled.
1254 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
1256 // Update the menu checkbox.
1257 menuItem.setChecked(firstPartyCookiesEnabled);
1259 // Apply the new cookie status.
1260 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1262 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1263 updatePrivacyIcons(true);
1265 // Display a `Snackbar`.
1266 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1267 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1268 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1269 Snackbar.make(findViewById(R.id.main_webview), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1270 } else { // Privacy mode.
1271 Snackbar.make(findViewById(R.id.main_webview), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1274 // Reload the WebView.
1275 mainWebView.reload();
1278 case R.id.toggle_third_party_cookies:
1279 if (Build.VERSION.SDK_INT >= 21) {
1280 // Switch the status of thirdPartyCookiesEnabled.
1281 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1283 // Update the menu checkbox.
1284 menuItem.setChecked(thirdPartyCookiesEnabled);
1286 // Apply the new cookie status.
1287 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1289 // Display a `Snackbar`.
1290 if (thirdPartyCookiesEnabled) {
1291 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1293 Snackbar.make(findViewById(R.id.main_webview), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1296 // Reload the WebView.
1297 mainWebView.reload();
1298 } // Else do nothing because SDK < 21.
1301 case R.id.toggle_dom_storage:
1302 // Switch the status of domStorageEnabled.
1303 domStorageEnabled = !domStorageEnabled;
1305 // Update the menu checkbox.
1306 menuItem.setChecked(domStorageEnabled);
1308 // Apply the new DOM Storage status.
1309 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1311 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1312 updatePrivacyIcons(true);
1314 // Display a `Snackbar`.
1315 if (domStorageEnabled) {
1316 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1318 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1321 // Reload the WebView.
1322 mainWebView.reload();
1325 case R.id.toggle_save_form_data:
1326 // Switch the status of saveFormDataEnabled.
1327 saveFormDataEnabled = !saveFormDataEnabled;
1329 // Update the menu checkbox.
1330 menuItem.setChecked(saveFormDataEnabled);
1332 // Apply the new form data status.
1333 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1335 // Display a `Snackbar`.
1336 if (saveFormDataEnabled) {
1337 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1339 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1342 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1343 updatePrivacyIcons(true);
1345 // Reload the WebView.
1346 mainWebView.reload();
1349 case R.id.clear_cookies:
1350 Snackbar.make(findViewById(R.id.main_webview), R.string.cookies_deleted, Snackbar.LENGTH_LONG)
1351 .setAction(R.string.undo, new View.OnClickListener() {
1353 public void onClick(View v) {
1354 // Do nothing because everything will be handled by `onDismissed()` below.
1357 .addCallback(new Snackbar.Callback() {
1359 public void onDismissed(Snackbar snackbar, int event) {
1361 // The user pushed the `Undo` button.
1362 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1366 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1368 // `cookieManager.removeAllCookie()` varies by SDK.
1369 if (Build.VERSION.SDK_INT < 21) {
1370 cookieManager.removeAllCookie();
1372 // `null` indicates no callback.
1373 cookieManager.removeAllCookies(null);
1381 case R.id.clear_dom_storage:
1382 Snackbar.make(findViewById(R.id.main_webview), R.string.dom_storage_deleted, Snackbar.LENGTH_LONG)
1383 .setAction(R.string.undo, new View.OnClickListener() {
1385 public void onClick(View v) {
1386 // Do nothing because everything will be handled by `onDismissed()` below.
1389 .addCallback(new Snackbar.Callback() {
1391 public void onDismissed(Snackbar snackbar, int event) {
1393 // The user pushed the `Undo` button.
1394 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1398 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1400 // Delete the DOM Storage.
1401 WebStorage webStorage = WebStorage.getInstance();
1402 webStorage.deleteAllData();
1404 // Manually remove `IndexedDB` if it exists.
1406 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1407 } catch (IOException e) {
1408 // Do nothing if an error is thrown.
1416 case R.id.clear_form_data:
1417 Snackbar.make(findViewById(R.id.main_webview), R.string.form_data_deleted, Snackbar.LENGTH_LONG)
1418 .setAction(R.string.undo, new View.OnClickListener() {
1420 public void onClick(View v) {
1421 // Do nothing because everything will be handled by `onDismissed()` below.
1424 .addCallback(new Snackbar.Callback() {
1426 public void onDismissed(Snackbar snackbar, int event) {
1428 // The user pushed the `Undo` button.
1429 case Snackbar.Callback.DISMISS_EVENT_ACTION:
1433 // The `Snackbar` was dismissed without the `Undo` button being pushed.
1435 // Delete the form data.
1436 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(getApplicationContext());
1437 mainWebViewDatabase.clearFormData();
1444 case R.id.font_size_twenty_five_percent:
1445 mainWebView.getSettings().setTextZoom(25);
1448 case R.id.font_size_fifty_percent:
1449 mainWebView.getSettings().setTextZoom(50);
1452 case R.id.font_size_seventy_five_percent:
1453 mainWebView.getSettings().setTextZoom(75);
1456 case R.id.font_size_one_hundred_percent:
1457 mainWebView.getSettings().setTextZoom(100);
1460 case R.id.font_size_one_hundred_twenty_five_percent:
1461 mainWebView.getSettings().setTextZoom(125);
1464 case R.id.font_size_one_hundred_fifty_percent:
1465 mainWebView.getSettings().setTextZoom(150);
1468 case R.id.font_size_one_hundred_seventy_five_percent:
1469 mainWebView.getSettings().setTextZoom(175);
1472 case R.id.font_size_two_hundred_percent:
1473 mainWebView.getSettings().setTextZoom(200);
1476 case R.id.display_images:
1477 if (mainWebView.getSettings().getLoadsImagesAutomatically()) { // Images are currently loaded automatically.
1478 mainWebView.getSettings().setLoadsImagesAutomatically(false);
1479 mainWebView.reload();
1480 } else { // Images are not currently loaded automatically.
1481 mainWebView.getSettings().setLoadsImagesAutomatically(true);
1484 // Set `onTheFlyDisplayImagesSet`.
1485 onTheFlyDisplayImagesSet = true;
1489 // Setup the share string.
1490 String shareString = webViewTitle + " – " + urlTextBox.getText().toString();
1492 // Create the share intent.
1493 Intent shareIntent = new Intent();
1494 shareIntent.setAction(Intent.ACTION_SEND);
1495 shareIntent.putExtra(Intent.EXTRA_TEXT, shareString);
1496 shareIntent.setType("text/plain");
1499 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1502 case R.id.find_on_page:
1503 // Hide the URL app bar.
1504 supportAppBar.setVisibility(View.GONE);
1506 // Show the Find on Page `RelativeLayout`.
1507 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1509 // 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
1510 findOnPageEditText.postDelayed(new Runnable()
1515 // Set the focus on `findOnPageEditText`.
1516 findOnPageEditText.requestFocus();
1518 // Display the keyboard. `0` sets no input flags.
1519 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1525 // Get a `PrintManager` instance.
1526 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1528 // Convert `mainWebView` to `printDocumentAdapter`.
1529 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1531 // Print the document. The print attributes are `null`.
1532 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1535 case R.id.add_to_homescreen:
1536 // Show the `CreateHomeScreenShortcutDialog` `AlertDialog` and name this instance `R.string.create_shortcut`.
1537 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcutDialog();
1538 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1540 //Everything else will be handled by `CreateHomeScreenShortcutDialog` and the associated listener below.
1544 mainWebView.reload();
1548 // Don't consume the event.
1549 return super.onOptionsItemSelected(menuItem);
1553 // removeAllCookies is deprecated, but it is required for API < 21.
1554 @SuppressWarnings("deprecation")
1556 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1557 int menuItemId = menuItem.getItemId();
1559 switch (menuItemId) {
1565 if (mainWebView.canGoBack()) {
1566 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1567 navigatingHistory = true;
1569 // Load the previous website in the history.
1570 mainWebView.goBack();
1575 if (mainWebView.canGoForward()) {
1576 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
1577 navigatingHistory = true;
1579 // Load the next website in the history.
1580 mainWebView.goForward();
1585 // Get the `WebBackForwardList`.
1586 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1588 // Show the `UrlHistoryDialog` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1589 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistoryDialog.loadBackForwardList(this, webBackForwardList);
1590 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1593 case R.id.bookmarks:
1594 // Launch BookmarksActivity.
1595 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
1596 startActivity(bookmarksIntent);
1599 case R.id.downloads:
1600 // Launch the system Download Manager.
1601 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1603 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1604 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1606 startActivity(downloadManagerIntent);
1610 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1611 currentDomainName = "";
1613 // Launch `SettingsActivity`.
1614 Intent settingsIntent = new Intent(this, SettingsActivity.class);
1615 startActivity(settingsIntent);
1619 // Reset `currentDomainName` so that domain settings are reapplied after returning to `MainWebViewActivity`.
1620 currentDomainName = "";
1622 // Launch `DomainsActivity`.
1623 Intent domainsIntent = new Intent(this, DomainsActivity.class);
1624 startActivity(domainsIntent);
1628 // Launch `GuideActivity`.
1629 Intent guideIntent = new Intent(this, GuideActivity.class);
1630 startActivity(guideIntent);
1634 // Launch `AboutActivity`.
1635 Intent aboutIntent = new Intent(this, AboutActivity.class);
1636 startActivity(aboutIntent);
1639 case R.id.clearAndExit:
1640 // Get a handle for `sharedPreferences`. `this` references the current context.
1641 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1643 boolean clearEverything = sharedPreferences.getBoolean("clear_everything", true);
1646 if (clearEverything || sharedPreferences.getBoolean("clear_cookies", true)) {
1647 // The command to remove cookies changed slightly in API 21.
1648 if (Build.VERSION.SDK_INT >= 21) {
1649 cookieManager.removeAllCookies(null);
1651 cookieManager.removeAllCookie();
1654 // Manually delete the cookies database, as `CookieManager` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1656 // We have to use two commands because `Runtime.exec()` does not like `*`.
1657 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies");
1658 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/Cookies-journal");
1659 } catch (IOException e) {
1660 // Do nothing if an error is thrown.
1664 // Clear DOM storage.
1665 if (clearEverything || sharedPreferences.getBoolean("clear_dom_storage", true)) {
1666 // Ask `WebStorage` to clear the DOM storage.
1667 WebStorage webStorage = WebStorage.getInstance();
1668 webStorage.deleteAllData();
1670 // Manually delete the DOM storage files and directories, as `WebStorage` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1672 // We have to use a `String[]` because the directory contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1673 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Local Storage/"});
1675 // We have to use multiple commands because `Runtime.exec()` does not like `*`.
1676 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/IndexedDB");
1677 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager");
1678 privacyBrowserRuntime.exec("rm -f " + privateDataDirectoryString + "/app_webview/QuotaManager-journal");
1679 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview/databases");
1680 } catch (IOException e) {
1681 // Do nothing if an error is thrown.
1686 if (clearEverything || sharedPreferences.getBoolean("clear_form_data", true)) {
1687 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1688 webViewDatabase.clearFormData();
1690 // Manually delete the form data database, as `WebViewDatabase` sometimes will not flush its changes to disk before `System.exit(0)` is run.
1692 // We have to use a `String[]` because the database contains a space and `Runtime.exec` will not escape the string correctly otherwise.
1693 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data"});
1694 privacyBrowserRuntime.exec(new String[] {"rm", "-f", privateDataDirectoryString + "/app_webview/Web Data-journal"});
1695 } catch (IOException e) {
1696 // Do nothing if an error is thrown.
1701 if (clearEverything || sharedPreferences.getBoolean("clear_cache", true)) {
1702 // `true` includes disk files.
1703 mainWebView.clearCache(true);
1705 // Manually delete the cache directories.
1707 // Delete the main cache directory.
1708 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/cache");
1710 // 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.
1711 privacyBrowserRuntime.exec(new String[] {"rm", "-rf", privateDataDirectoryString + "/app_webview/Service Worker/"});
1712 } catch (IOException e) {
1713 // Do nothing if an error is thrown.
1717 // Clear SSL certificate preferences.
1718 mainWebView.clearSslPreferences();
1720 // Clear the back/forward history.
1721 mainWebView.clearHistory();
1723 // Clear `formattedUrlString`.
1724 formattedUrlString = null;
1726 // Clear `customHeaders`.
1727 customHeaders.clear();
1729 // Detach all views from `mainWebViewRelativeLayout`.
1730 mainWebViewRelativeLayout.removeAllViews();
1732 // Destroy the internal state of `mainWebView`.
1733 mainWebView.destroy();
1735 // Manually delete the `app_webview` folder, which contains the cookies, DOM storage, form data, and `Service Worker` cache.
1736 // See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1737 if (clearEverything) {
1739 privacyBrowserRuntime.exec("rm -rf " + privateDataDirectoryString + "/app_webview");
1740 } catch (IOException e) {
1741 // Do nothing if an error is thrown.
1745 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1746 if (Build.VERSION.SDK_INT >= 21) {
1747 finishAndRemoveTask();
1752 // Remove the terminated program from RAM. The status code is `0`.
1757 // Close the navigation drawer.
1758 drawerLayout.closeDrawer(GravityCompat.START);
1763 public void onPostCreate(Bundle savedInstanceState) {
1764 super.onPostCreate(savedInstanceState);
1766 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1767 drawerToggle.syncState();
1771 public void onConfigurationChanged(Configuration newConfig) {
1772 super.onConfigurationChanged(newConfig);
1774 // Reload the ad for the free flavor if we are not in full screen mode.
1775 if (BuildConfig.FLAVOR.contentEquals("free") && !inFullScreenBrowsingMode) {
1777 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1779 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1780 adView = findViewById(R.id.adview);
1783 // `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
1784 // ActivityCompat.invalidateOptionsMenu(this);
1788 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1789 // Store the `HitTestResult`.
1790 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1793 final String imageUrl;
1794 final String linkUrl;
1796 // Get a handle for the `ClipboardManager`.
1797 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1799 switch (hitTestResult.getType()) {
1800 // `SRC_ANCHOR_TYPE` is a link.
1801 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1802 // Get the target URL.
1803 linkUrl = hitTestResult.getExtra();
1805 // Set the target URL as the title of the `ContextMenu`.
1806 menu.setHeaderTitle(linkUrl);
1808 // Add a `Load URL` entry.
1809 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1811 public boolean onMenuItemClick(MenuItem item) {
1817 // Add a `Copy URL` entry.
1818 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1820 public boolean onMenuItemClick(MenuItem item) {
1821 // Save the link URL in a `ClipData`.
1822 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1824 // Set the `ClipData` as the clipboard's primary clip.
1825 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1830 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1831 menu.add(R.string.cancel);
1834 case WebView.HitTestResult.EMAIL_TYPE:
1835 // Get the target URL.
1836 linkUrl = hitTestResult.getExtra();
1838 // Set the target URL as the title of the `ContextMenu`.
1839 menu.setHeaderTitle(linkUrl);
1841 // Add a `Write Email` entry.
1842 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1844 public boolean onMenuItemClick(MenuItem item) {
1845 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1846 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1848 // Parse the url and set it as the data for the `Intent`.
1849 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1851 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1852 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1855 startActivity(emailIntent);
1860 // Add a `Copy Email Address` entry.
1861 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1863 public boolean onMenuItemClick(MenuItem item) {
1864 // Save the email address in a `ClipData`.
1865 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1867 // Set the `ClipData` as the clipboard's primary clip.
1868 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1873 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1874 menu.add(R.string.cancel);
1877 // `IMAGE_TYPE` is an image.
1878 case WebView.HitTestResult.IMAGE_TYPE:
1879 // Get the image URL.
1880 imageUrl = hitTestResult.getExtra();
1882 // Set the image URL as the title of the `ContextMenu`.
1883 menu.setHeaderTitle(imageUrl);
1885 // Add a `View Image` entry.
1886 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1888 public boolean onMenuItemClick(MenuItem item) {
1894 // Add a `Download Image` entry.
1895 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1897 public boolean onMenuItemClick(MenuItem item) {
1898 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1899 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1900 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1905 // Add a `Copy URL` entry.
1906 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1908 public boolean onMenuItemClick(MenuItem item) {
1909 // Save the image URL in a `ClipData`.
1910 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1912 // Set the `ClipData` as the clipboard's primary clip.
1913 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1918 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1919 menu.add(R.string.cancel);
1923 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1924 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1925 // Get the image URL.
1926 imageUrl = hitTestResult.getExtra();
1928 // Set the image URL as the title of the `ContextMenu`.
1929 menu.setHeaderTitle(imageUrl);
1931 // Add a `View Image` entry.
1932 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1934 public boolean onMenuItemClick(MenuItem item) {
1940 // Add a `Download Image` entry.
1941 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1943 public boolean onMenuItemClick(MenuItem item) {
1944 // Show the `DownloadImageDialog` `AlertDialog` and name this instance `@string/download`.
1945 AppCompatDialogFragment downloadImageDialogFragment = DownloadImageDialog.imageUrl(imageUrl);
1946 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1951 // Add a `Copy URL` entry.
1952 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1954 public boolean onMenuItemClick(MenuItem item) {
1955 // Save the image URL in a `ClipData`.
1956 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1958 // Set the `ClipData` as the clipboard's primary clip.
1959 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1964 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1965 menu.add(R.string.cancel);
1971 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1972 // Get shortcutNameEditText from the alert dialog.
1973 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1975 // Create the bookmark shortcut based on formattedUrlString.
1976 Intent bookmarkShortcut = new Intent();
1977 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1978 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1980 // Place the bookmark shortcut on the home screen.
1981 Intent placeBookmarkShortcut = new Intent();
1982 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1983 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1984 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIconBitmap);
1985 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1986 sendBroadcast(placeBookmarkShortcut);
1990 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1991 // Download the image if it has an HTTP or HTTPS URI.
1992 if (imageUrl.startsWith("http")) {
1993 // Get a handle for the system `DOWNLOAD_SERVICE`.
1994 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1996 // Parse `imageUrl`.
1997 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1999 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
2000 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2001 if (firstPartyCookiesEnabled) {
2002 // Get the cookies for `imageUrl`.
2003 String cookies = cookieManager.getCookie(imageUrl);
2005 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2006 downloadRequest.addRequestHeader("Cookie", cookies);
2009 // Get the file name from `dialogFragment`.
2010 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
2011 String imageName = downloadImageNameEditText.getText().toString();
2013 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2014 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
2015 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
2016 } else { // Only set the title using `imageName`.
2017 downloadRequest.setTitle(imageName);
2020 // Allow `MediaScanner` to index the download if it is a media file.
2021 downloadRequest.allowScanningByMediaScanner();
2023 // Add the URL as the description for the download.
2024 downloadRequest.setDescription(imageUrl);
2026 // Show the download notification after the download is completed.
2027 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2029 // Initiate the download.
2030 downloadManager.enqueue(downloadRequest);
2031 } else { // The image is not an HTTP or HTTPS URI.
2032 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
2037 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
2038 // Download the file if it has an HTTP or HTTPS URI.
2039 if (downloadUrl.startsWith("http")) {
2041 // Get a handle for the system `DOWNLOAD_SERVICE`.
2042 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
2044 // Parse `downloadUrl`.
2045 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
2047 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
2048 // Code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
2049 if (firstPartyCookiesEnabled) {
2050 // Get the cookies for `downloadUrl`.
2051 String cookies = cookieManager.getCookie(downloadUrl);
2053 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
2054 downloadRequest.addRequestHeader("Cookie", cookies);
2057 // Get the file name from `dialogFragment`.
2058 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
2059 String fileName = downloadFileNameEditText.getText().toString();
2061 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
2062 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
2063 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
2064 } else { // Only set the title using `fileName`.
2065 downloadRequest.setTitle(fileName);
2068 // Allow `MediaScanner` to index the download if it is a media file.
2069 downloadRequest.allowScanningByMediaScanner();
2071 // Add the URL as the description for the download.
2072 downloadRequest.setDescription(downloadUrl);
2074 // Show the download notification after the download is completed.
2075 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2077 // Initiate the download.
2078 downloadManager.enqueue(downloadRequest);
2079 } else { // The download is not an HTTP or HTTPS URI.
2080 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
2084 public void viewSslCertificate(View view) {
2085 // Show the `ViewSslCertificateDialog` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
2086 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificateDialog();
2087 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
2091 public void onSslErrorCancel() {
2092 sslErrorHandler.cancel();
2096 public void onSslErrorProceed() {
2097 sslErrorHandler.proceed();
2101 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
2102 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2103 navigatingHistory = true;
2105 // Load the history entry.
2106 mainWebView.goBackOrForward(moveBackOrForwardSteps);
2110 public void onClearHistory() {
2111 // Clear the history.
2112 mainWebView.clearHistory();
2115 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
2117 public void onBackPressed() {
2118 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
2119 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
2120 drawerLayout.closeDrawer(GravityCompat.START);
2122 // Load the previous URL if available.
2123 if (mainWebView.canGoBack()) {
2124 // Set `navigatingHistory` so that the domain settings are applied when the new URL is loaded.
2125 navigatingHistory = true;
2128 mainWebView.goBack();
2130 // Pass `onBackPressed()` to the system.
2131 super.onBackPressed();
2136 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
2137 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
2138 String unformattedUrlString = urlTextBox.getText().toString().trim();
2140 // Check to see if `unformattedUrlString` is a valid URL. Otherwise, convert it into a search.
2141 if ((Patterns.WEB_URL.matcher(unformattedUrlString).matches()) || (unformattedUrlString.startsWith("http://")) || (unformattedUrlString.startsWith("https://"))) {
2142 // Add `http://` at the beginning if it is missing. Otherwise the app will segfault.
2143 if (!unformattedUrlString.startsWith("http")) {
2144 unformattedUrlString = "http://" + unformattedUrlString;
2147 // Initialize `unformattedUrl`.
2148 URL unformattedUrl = null;
2150 // 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.
2152 unformattedUrl = new URL(unformattedUrlString);
2153 } catch (MalformedURLException e) {
2154 e.printStackTrace();
2157 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if `.get` was called on a `null` value.
2158 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
2159 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
2160 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
2161 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
2162 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
2165 Uri.Builder formattedUri = new Uri.Builder();
2166 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
2168 // Decode `formattedUri` as a `String` in `UTF-8`.
2169 formattedUrlString = URLDecoder.decode(formattedUri.build().toString(), "UTF-8");
2171 // Sanitize the search input and convert it to a search.
2172 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
2174 // Add the base search URL.
2175 formattedUrlString = searchURL + encodedUrlString;
2178 loadUrl(formattedUrlString);
2180 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2181 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2185 private void loadUrl(String url) {
2186 // Apply any custom domain settings.
2187 applyDomainSettings(url);
2190 mainWebView.loadUrl(url, customHeaders);
2192 // Set `urlIsLoading` to prevent changes in the user agent on websites with redirects from reloading the current website.
2193 urlIsLoading = true;
2196 public void findPreviousOnPage(View view) {
2197 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
2198 mainWebView.findNext(false);
2201 public void findNextOnPage(View view) {
2202 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
2203 mainWebView.findNext(true);
2206 public void closeFindOnPage(View view) {
2207 // Delete the contents of `find_on_page_edittext`.
2208 findOnPageEditText.setText(null);
2210 // Clear the highlighted phrases.
2211 mainWebView.clearMatches();
2213 // Hide the Find on Page `RelativeLayout`.
2214 findOnPageLinearLayout.setVisibility(View.GONE);
2216 // Show the URL app bar.
2217 supportAppBar.setVisibility(View.VISIBLE);
2219 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
2220 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
2223 private void applyAppSettings() {
2224 // Get a handle for `sharedPreferences`. `this` references the current context.
2225 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2227 // Store the values from `sharedPreferences` in variables.
2228 String homepageString = sharedPreferences.getString("homepage", "https://start.duckduckgo.com");
2229 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
2230 String torSearchString = sharedPreferences.getString("tor_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
2231 String torSearchCustomURLString = sharedPreferences.getString("tor_search_custom_url", "");
2232 String searchString = sharedPreferences.getString("search", "https://duckduckgo.com/html/?q=");
2233 String searchCustomURLString = sharedPreferences.getString("search_custom_url", "");
2234 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
2235 incognitoModeEnabled = sharedPreferences.getBoolean("incognito_mode", false);
2236 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
2237 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
2238 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("full_screen_browsing_mode", false);
2239 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
2240 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
2241 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh", false);
2242 displayWebpageImagesBoolean = sharedPreferences.getBoolean("display_webpage_images", true);
2244 // Set the homepage, search, and proxy options.
2245 if (proxyThroughOrbot) { // Set the Tor options.
2246 // Set `torHomepageString` as `homepage`.
2247 homepage = torHomepageString;
2249 // If formattedUrlString is null assign the homepage to it.
2250 if (formattedUrlString == null) {
2251 formattedUrlString = homepage;
2254 // Set the search URL.
2255 if (torSearchString.equals("Custom URL")) { // Get the custom URL string.
2256 searchURL = torSearchCustomURLString;
2257 } else { // Use the string from the pre-built list.
2258 searchURL = torSearchString;
2261 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
2262 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
2264 // Set the `appBar` background to indicate proxying through Orbot is enabled. `this` refers to the context.
2266 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.dark_blue_30));
2268 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.blue_50));
2271 // Display a message to the user if we are waiting on Orbot.
2272 if (!orbotStatus.equals("ON")) {
2273 // Set `waitingForOrbot`.
2274 waitingForOrbot = true;
2276 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
2277 mainWebView.loadData(waitingForOrbotHTMLString, "text/html", null);
2279 } else { // Set the non-Tor options.
2280 // Set `homepageString` as `homepage`.
2281 homepage = homepageString;
2283 // If formattedUrlString is null assign the homepage to it.
2284 if (formattedUrlString == null) {
2285 formattedUrlString = homepage;
2288 // Set the search URL.
2289 if (searchString.equals("Custom URL")) { // Get the custom URL string.
2290 searchURL = searchCustomURLString;
2291 } else { // Use the string from the pre-built list.
2292 searchURL = searchString;
2295 // Reset the proxy to default. The host is `""` and the port is `"0"`.
2296 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
2298 // Set the default `appBar` background. `this` refers to the context.
2300 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_900));
2302 appBar.setBackgroundDrawable(ContextCompat.getDrawable(this, R.color.gray_100));
2305 // Reset `waitingForOrbot.
2306 waitingForOrbot = false;
2309 // Set swipe to refresh.
2310 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
2312 // Set Do Not Track status.
2313 if (doNotTrackEnabled) {
2314 customHeaders.put("DNT", "1");
2316 customHeaders.remove("DNT");
2319 // Apply the appropriate full screen mode the `SYSTEM_UI` flags.
2320 if (fullScreenBrowsingModeEnabled && inFullScreenBrowsingMode) {
2321 if (hideSystemBarsOnFullscreen) { // Hide everything.
2322 // Remove the translucent navigation setting if it is currently flagged.
2323 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2325 // Remove the translucent status bar overlay.
2326 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2328 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
2329 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
2331 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
2332 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
2333 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
2335 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
2336 } else { // Hide everything except the status and navigation bars.
2337 // Add the translucent status flag if it is unset.
2338 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2340 if (translucentNavigationBarOnFullscreen) {
2341 // Set the navigation bar to be translucent.
2342 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2344 // Set the navigation bar to be black.
2345 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2348 } else { // Switch to normal viewing mode.
2349 // Reset `inFullScreenBrowsingMode` to `false`.
2350 inFullScreenBrowsingMode = false;
2352 // Show the `appBar` if `findOnPageLinearLayout` is not visible.
2353 if (findOnPageLinearLayout.getVisibility() == View.GONE) {
2357 // Show the `BannerAd` in the free flavor.
2358 if (BuildConfig.FLAVOR.contentEquals("free")) {
2359 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
2360 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
2362 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
2363 adView = findViewById(R.id.adview);
2366 // Remove the translucent navigation bar flag if it is set.
2367 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
2369 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
2370 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
2372 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
2373 rootCoordinatorLayout.setSystemUiVisibility(0);
2375 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
2376 rootCoordinatorLayout.setFitsSystemWindows(true);
2380 // We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2381 @SuppressWarnings("deprecation")
2382 private void applyDomainSettings(String url) {
2383 // Reset `navigatingHistory`.
2384 navigatingHistory = false;
2386 // Parse the URL into a URI.
2387 Uri uri = Uri.parse(url);
2389 // Extract the domain from `uri`.
2390 String hostName = uri.getHost();
2392 // Initialize `loadingNewDomainName`.
2393 boolean loadingNewDomainName;
2395 // If either `hostName` or `currentDomainName` are `null`, run the options for loading a new domain name.
2396 // The lint suggestion to simplify the `if` statement is incorrect, because `hostName.equals(currentDomainName)` can produce a `null object reference.`
2397 //noinspection SimplifiableIfStatement
2398 if ((hostName == null) || (currentDomainName == null)) {
2399 loadingNewDomainName = true;
2400 } else { // Determine if `hostName` equals `currentDomainName`.
2401 loadingNewDomainName = !hostName.equals(currentDomainName);
2404 // 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.
2405 if (loadingNewDomainName) {
2406 // Set the new `hostname` as the `currentDomainName`.
2407 currentDomainName = hostName;
2409 // Reset `favoriteIconBitmap` and display it in the `appbar`.
2410 favoriteIconBitmap = favoriteIconDefaultBitmap;
2411 favoriteIconImageView.setImageBitmap(Bitmap.createScaledBitmap(favoriteIconBitmap, 64, 64, true));
2413 // Initialize the database handler. `this` specifies the context. The two `nulls` do not specify the database name or a `CursorFactory`.
2414 // The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
2415 DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(this, null, null, 0);
2417 // Get a full cursor from `domainsDatabaseHelper`.
2418 Cursor domainNameCursor = domainsDatabaseHelper.getDomainNameCursorOrderedByDomain();
2420 // Initialize `domainSettingsSet`.
2421 Set<String> domainSettingsSet = new HashSet<>();
2423 // Get the domain name column index.
2424 int domainNameColumnIndex = domainNameCursor.getColumnIndex(DomainsDatabaseHelper.DOMAIN_NAME);
2426 // Populate `domainSettingsSet`.
2427 for (int i = 0; i < domainNameCursor.getCount(); i++) {
2428 // Move `domainsCursor` to the current row.
2429 domainNameCursor.moveToPosition(i);
2431 // Store the domain name in `domainSettingsSet`.
2432 domainSettingsSet.add(domainNameCursor.getString(domainNameColumnIndex));
2435 // Close `domainNameCursor.
2436 domainNameCursor.close();
2438 // Initialize variables to track if domain settings will be applied and, if so, under which name.
2439 domainSettingsApplied = false;
2440 String domainNameInDatabase = null;
2442 // Check the hostname.
2443 if (domainSettingsSet.contains(hostName)) {
2444 domainSettingsApplied = true;
2445 domainNameInDatabase = hostName;
2448 // If `hostName` is not `null`, check all the subdomains of `hostName` against wildcard domains in `domainCursor`.
2449 if (hostName != null) {
2450 while (hostName.contains(".") && !domainSettingsApplied) { // Stop checking if we run out of `.` or if we already know that `domainSettingsApplied` is `true`.
2451 if (domainSettingsSet.contains("*." + hostName)) { // Check the host name prepended by `*.`.
2452 domainSettingsApplied = true;
2453 domainNameInDatabase = "*." + hostName;
2456 // Strip out the lowest subdomain of `host`.
2457 hostName = hostName.substring(hostName.indexOf(".") + 1);
2461 // Get a handle for the shared preference. `this` references the current context.
2462 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
2464 // Store the default font size and user agent information.
2465 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
2466 String defaultUserAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
2467 String defaultCustomUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
2469 if (domainSettingsApplied) { // The url we are loading has custom domain settings.
2470 // Get a cursor for the current host and move it to the first position.
2471 Cursor currentHostDomainSettingsCursor = domainsDatabaseHelper.getCursorForDomainName(domainNameInDatabase);
2472 currentHostDomainSettingsCursor.moveToFirst();
2474 // Get the settings from the cursor.
2475 javaScriptEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_JAVASCRIPT)) == 1);
2476 firstPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FIRST_PARTY_COOKIES)) == 1);
2477 thirdPartyCookiesEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_THIRD_PARTY_COOKIES)) == 1);
2478 domStorageEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_DOM_STORAGE)) == 1);
2479 saveFormDataEnabled = (currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.ENABLE_FORM_DATA)) == 1);
2480 String userAgentString = currentHostDomainSettingsCursor.getString(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.USER_AGENT));
2481 int fontSize = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.FONT_SIZE));
2482 displayWebpageImagesInt = currentHostDomainSettingsCursor.getInt(currentHostDomainSettingsCursor.getColumnIndex(DomainsDatabaseHelper.DISPLAY_IMAGES));
2484 // Close `currentHostDomainSettingsCursor`.
2485 currentHostDomainSettingsCursor.close();
2487 // Apply the domain settings.
2488 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2489 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2490 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2491 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2493 // Apply the font size.
2494 if (fontSize == 0) { // Apply the default font size.
2495 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2496 } else { // Apply the specified font size.
2497 mainWebView.getSettings().setTextZoom(fontSize);
2500 // Set third-party cookies status if API >= 21.
2501 if (Build.VERSION.SDK_INT >= 21) {
2502 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2505 // 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>
2506 if (!urlIsLoading) {
2507 switch (userAgentString) {
2508 case "System default user agent":
2509 // Set the user agent according to the system default.
2510 switch (defaultUserAgentString) {
2511 case "WebView default user agent":
2512 // Set the user agent to `""`, which uses the default value.
2513 mainWebView.getSettings().setUserAgentString("");
2516 case "Custom user agent":
2517 // Set the custom user agent.
2518 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2522 // Use the selected user agent.
2523 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2527 case "WebView default user agent":
2528 // Set the user agent to `""`, which uses the default value.
2529 mainWebView.getSettings().setUserAgentString("");
2533 // Use the selected user agent.
2534 mainWebView.getSettings().setUserAgentString(userAgentString);
2538 // 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.
2540 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_dark_blue));
2542 urlAppBarRelativeLayout.setBackground(getResources().getDrawable(R.drawable.url_bar_background_light_green));
2544 } else { // The URL we are loading does not have custom domain settings. Load the defaults.
2545 // Store the values from `sharedPreferences` in variables.
2546 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
2547 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
2548 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
2549 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
2550 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
2552 // Apply the default settings.
2553 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
2554 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
2555 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
2556 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
2557 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
2559 // Set third-party cookies status if API >= 21.
2560 if (Build.VERSION.SDK_INT >= 21) {
2561 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
2564 // 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>
2565 if (!urlIsLoading) {
2566 switch (defaultUserAgentString) {
2567 case "WebView default user agent":
2568 // Set the user agent to `""`, which uses the default value.
2569 mainWebView.getSettings().setUserAgentString("");
2572 case "Custom user agent":
2573 // Set the custom user agent.
2574 mainWebView.getSettings().setUserAgentString(defaultCustomUserAgentString);
2578 // Use the selected user agent.
2579 mainWebView.getSettings().setUserAgentString(defaultUserAgentString);
2583 // Set a transparent background on `urlTextBox`. We have to use the deprecated `.getDrawable()` until the minimum API >= 21.
2584 urlAppBarRelativeLayout.setBackgroundDrawable(getResources().getDrawable(R.color.transparent));
2587 // Close `domainsDatabaseHelper`.
2588 domainsDatabaseHelper.close();
2590 // Remove the `onTheFlyDisplayImagesSet` flag and set the display webpage images mode. `true` indicates that custom domain settings are applied.
2591 onTheFlyDisplayImagesSet = false;
2592 setDisplayWebpageImages();
2594 // Update the privacy icons, but only if `mainMenu` has already been populated.
2595 if (mainMenu != null) {
2596 updatePrivacyIcons(true);
2601 private void setDisplayWebpageImages() {
2602 if (!onTheFlyDisplayImagesSet) {
2603 if (domainSettingsApplied) { // Custom domain settings are applied.
2604 switch (displayWebpageImagesInt) {
2605 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_SYSTEM_DEFAULT:
2606 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2609 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_ENABLED:
2610 mainWebView.getSettings().setLoadsImagesAutomatically(true);
2613 case DomainsDatabaseHelper.DISPLAY_WEBPAGE_IMAGES_DISABLED:
2614 mainWebView.getSettings().setLoadsImagesAutomatically(false);
2617 } else { // Default settings are applied.
2618 mainWebView.getSettings().setLoadsImagesAutomatically(displayWebpageImagesBoolean);
2623 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
2624 // Get handles for the icons.
2625 MenuItem privacyIconMenuItem = mainMenu.findItem(R.id.toggle_javascript);
2626 MenuItem firstPartyCookiesIconMenuItem = mainMenu.findItem(R.id.toggle_first_party_cookies);
2627 MenuItem domStorageIconMenuItem = mainMenu.findItem(R.id.toggle_dom_storage);
2628 MenuItem formDataIconMenuItem = mainMenu.findItem(R.id.toggle_save_form_data);
2630 // Update `privacyIcon`.
2631 if (javaScriptEnabled) { // JavaScript is enabled.
2632 privacyIconMenuItem.setIcon(R.drawable.javascript_enabled);
2633 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
2634 privacyIconMenuItem.setIcon(R.drawable.warning);
2635 } else { // All the dangerous features are disabled.
2636 privacyIconMenuItem.setIcon(R.drawable.privacy_mode);
2639 // Update `firstPartyCookiesIcon`.
2640 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
2641 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_enabled);
2642 } else { // First-party cookies are disabled.
2644 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_dark);
2646 firstPartyCookiesIconMenuItem.setIcon(R.drawable.cookies_disabled_light);
2650 // Update `domStorageIcon`.
2651 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
2652 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_enabled);
2653 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2655 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_dark);
2657 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_disabled_light);
2659 } else { // JavaScript is disabled, so DOM storage is ghosted.
2661 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_dark);
2663 domStorageIconMenuItem.setIcon(R.drawable.dom_storage_ghosted_light);
2667 // Update `formDataIcon`.
2668 if (saveFormDataEnabled) { // Form data is enabled.
2669 formDataIconMenuItem.setIcon(R.drawable.form_data_enabled);
2670 } else { // Form data is disabled.
2672 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_dark);
2674 formDataIconMenuItem.setIcon(R.drawable.form_data_disabled_light);
2678 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2679 if (runInvalidateOptionsMenu) {
2680 ActivityCompat.invalidateOptionsMenu(this);
2684 private void highlightUrlText() {
2685 String urlString = urlTextBox.getText().toString();
2687 if (urlString.startsWith("http://")) { // Highlight connections that are not encrypted.
2688 urlTextBox.getText().setSpan(redColorSpan, 0, 7, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2689 } else if (urlString.startsWith("https://")) { // Highlight connections that are encrypted.
2690 urlTextBox.getText().setSpan(initialGrayColorSpan, 0, 8, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
2693 // Get the index of the `/` immediately after the domain name.
2694 int endOfDomainName = urlString.indexOf("/", (urlString.indexOf("//") + 2));
2696 // De-emphasize the text after the domain name.
2697 if (endOfDomainName > 0) {
2698 urlTextBox.getText().setSpan(finalGrayColorSpan, endOfDomainName, urlString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);