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.ClipData;
28 import android.content.ClipboardManager;
29 import android.content.Context;
30 import android.content.Intent;
31 import android.content.SharedPreferences;
32 import android.content.res.Configuration;
33 import android.graphics.Bitmap;
34 import android.graphics.drawable.BitmapDrawable;
35 import android.graphics.drawable.Drawable;
36 import android.net.Uri;
37 import android.net.http.SslCertificate;
38 import android.net.http.SslError;
39 import android.os.Build;
40 import android.os.Bundle;
41 import android.preference.PreferenceManager;
42 import android.print.PrintDocumentAdapter;
43 import android.print.PrintManager;
44 import android.support.annotation.NonNull;
45 import android.support.design.widget.CoordinatorLayout;
46 import android.support.design.widget.NavigationView;
47 import android.support.design.widget.Snackbar;
48 import android.support.v4.app.ActivityCompat;
49 import android.support.v4.content.ContextCompat;
50 import android.support.v4.view.GravityCompat;
51 import android.support.v4.widget.DrawerLayout;
52 import android.support.v4.widget.SwipeRefreshLayout;
53 import android.support.v7.app.ActionBar;
54 import android.support.v7.app.ActionBarDrawerToggle;
55 import android.support.v7.app.AppCompatActivity;
56 import android.support.v7.app.AppCompatDialogFragment;
57 import android.support.v7.widget.Toolbar;
58 import android.text.Editable;
59 import android.text.TextWatcher;
60 import android.util.Patterns;
61 import android.view.ContextMenu;
62 import android.view.GestureDetector;
63 import android.view.KeyEvent;
64 import android.view.Menu;
65 import android.view.MenuItem;
66 import android.view.MotionEvent;
67 import android.view.View;
68 import android.view.WindowManager;
69 import android.view.inputmethod.InputMethodManager;
70 import android.webkit.CookieManager;
71 import android.webkit.DownloadListener;
72 import android.webkit.SslErrorHandler;
73 import android.webkit.WebBackForwardList;
74 import android.webkit.WebChromeClient;
75 import android.webkit.WebResourceResponse;
76 import android.webkit.WebStorage;
77 import android.webkit.WebView;
78 import android.webkit.WebViewClient;
79 import android.webkit.WebViewDatabase;
80 import android.widget.EditText;
81 import android.widget.FrameLayout;
82 import android.widget.ImageView;
83 import android.widget.LinearLayout;
84 import android.widget.ProgressBar;
85 import android.widget.RelativeLayout;
86 import android.widget.TextView;
88 import com.stoutner.privacybrowser.BannerAd;
89 import com.stoutner.privacybrowser.BuildConfig;
90 import com.stoutner.privacybrowser.R;
91 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
92 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcut;
93 import com.stoutner.privacybrowser.dialogs.DownloadFile;
94 import com.stoutner.privacybrowser.dialogs.DownloadImage;
95 import com.stoutner.privacybrowser.dialogs.SslCertificateError;
96 import com.stoutner.privacybrowser.dialogs.UrlHistory;
97 import com.stoutner.privacybrowser.dialogs.ViewSslCertificate;
99 import java.io.BufferedReader;
100 import java.io.ByteArrayInputStream;
101 import java.io.IOException;
102 import java.io.InputStreamReader;
103 import java.io.UnsupportedEncodingException;
104 import java.net.MalformedURLException;
106 import java.net.URLEncoder;
107 import java.util.HashMap;
108 import java.util.HashSet;
109 import java.util.Map;
110 import java.util.Set;
112 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
113 public class MainWebView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
114 SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener, DownloadImage.DownloadImageListener, UrlHistory.UrlHistoryListener {
116 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
117 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applySettings()`.
118 public static ActionBar appBar;
120 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `Bookmarks`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
121 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
122 public static Bitmap favoriteIcon;
124 // `formattedUrlString` is public static so it can be accessed from `Bookmarks`.
125 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
126 public static String formattedUrlString;
128 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`. It is also used in `onCreate()`.
129 public static SslCertificate sslCertificate;
132 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
133 private DrawerLayout drawerLayout;
135 // `rootCoordinatorLayout` is used in `onCreate()` and `applySettings()`.
136 private CoordinatorLayout rootCoordinatorLayout;
138 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
139 private WebView mainWebView;
141 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
142 private FrameLayout fullScreenVideoFrameLayout;
144 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
145 private SwipeRefreshLayout swipeRefreshLayout;
147 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
148 private CookieManager cookieManager;
150 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrlFromTextBox()`.
151 private final Map<String, String> customHeaders = new HashMap<>();
153 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
154 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
155 private Boolean javaScriptEnabled;
157 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applySettings()`.
158 private boolean firstPartyCookiesEnabled;
160 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
161 private boolean thirdPartyCookiesEnabled;
163 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
164 private boolean domStorageEnabled;
166 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
167 private boolean saveFormDataEnabled;
169 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
170 private boolean swipeToRefreshEnabled;
172 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
173 private String homepage;
175 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
176 private String javaScriptDisabledSearchURL;
178 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
179 private String javaScriptEnabledSearchURL;
181 // `adBlockerEnabled` is used in `onCreate()` and `applySettings()`.
182 private boolean adBlockerEnabled;
184 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applySettings()`.
185 private boolean fullScreenBrowsingModeEnabled;
187 // `inFullScreenBrowsingMode` is used in `onCreate()` and `applySettings()`.
188 private boolean inFullScreenBrowsingMode;
190 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
191 private boolean hideSystemBarsOnFullscreen;
193 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
194 private boolean translucentNavigationBarOnFullscreen;
196 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
197 private LinearLayout findOnPageLinearLayout;
199 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
200 private EditText findOnPageEditText;
202 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
203 private Menu mainMenu;
205 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
206 private ActionBarDrawerToggle drawerToggle;
208 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
209 private Toolbar supportAppBar;
211 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
212 private EditText urlTextBox;
214 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
217 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
218 private SslErrorHandler sslErrorHandler;
220 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
221 private InputMethodManager inputMethodManager;
223 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
224 private RelativeLayout mainWebViewRelativeLayout;
227 // 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.
228 @SuppressLint("SetJavaScriptEnabled")
229 protected void onCreate(Bundle savedInstanceState) {
230 super.onCreate(savedInstanceState);
231 setContentView(R.layout.drawerlayout);
233 // Get a handle for `inputMethodManager`.
234 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
236 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
237 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
238 setSupportActionBar(supportAppBar);
239 appBar = getSupportActionBar();
241 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
242 assert appBar != null;
244 // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
245 appBar.setCustomView(R.layout.url_app_bar);
246 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
248 // Set the "go" button on the keyboard to load the URL in urlTextBox.
249 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
250 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
252 public boolean onKey(View v, int keyCode, KeyEvent event) {
253 // If the event is a key-down event on the `enter` button, load the URL.
254 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
255 // Load the URL into the mainWebView and consume the event.
257 loadUrlFromTextBox();
258 } catch (UnsupportedEncodingException e) {
261 // If the enter key was pressed, consume the event.
264 // If any other key was pressed, do not consume the event.
270 // Get handles for views that need to be accessed.
271 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
272 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
273 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
274 mainWebView = (WebView) findViewById(R.id.mainWebView);
275 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
276 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
277 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
279 // Create a double-tap listener to toggle full-screen mode.
280 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
281 // Override `onDoubleTap()`. All other events are handled using the default settings.
283 public boolean onDoubleTap(MotionEvent event) {
284 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
285 // Toggle `inFullScreenBrowsingMode`.
286 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
288 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
289 // Hide the `appBar`.
292 // Hide the `BannerAd` in the free flavor.
293 if (BuildConfig.FLAVOR.contentEquals("free")) {
294 BannerAd.hideAd(adView);
297 // Modify the system bars.
298 if (hideSystemBarsOnFullscreen) { // Hide everything.
299 // Remove the translucent overlays.
300 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
302 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
303 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
305 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
306 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
307 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
309 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
311 // Set `rootCoordinatorLayout` to fill the whole screen.
312 rootCoordinatorLayout.setFitsSystemWindows(false);
313 } else { // Hide everything except the status and navigation bars.
314 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
315 rootCoordinatorLayout.setFitsSystemWindows(false);
317 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.
318 // Set the navigation bar to be translucent.
319 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
322 } else { // Switch to normal viewing mode.
323 // Show the `appBar`.
326 // Show the `BannerAd` in the free flavor.
327 if (BuildConfig.FLAVOR.contentEquals("free")) {
328 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
329 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
331 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
332 adView = findViewById(R.id.adView);
335 // Remove the translucent navigation bar flag if it is set.
336 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
338 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
339 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
341 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
342 rootCoordinatorLayout.setSystemUiVisibility(0);
344 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
345 rootCoordinatorLayout.setFitsSystemWindows(true);
348 // Consume the double-tap.
350 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
356 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
357 mainWebView.setOnTouchListener(new View.OnTouchListener() {
359 public boolean onTouch(View v, MotionEvent event) {
360 // Send the `event` to `gestureDetector`.
361 return gestureDetector.onTouchEvent(event);
365 // Update `findOnPageCountTextView`.
366 mainWebView.setFindListener(new WebView.FindListener() {
367 // Get a handle for `findOnPageCountTextView`.
368 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
371 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
372 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
373 // Set `findOnPageCountTextView` to `0/0`.
374 findOnPageCountTextView.setText(R.string.zero_of_zero);
375 } else if (isDoneCounting) { // There are matches.
376 // `activeMatchOrdinal` is zero-based.
377 int activeMatch = activeMatchOrdinal + 1;
379 // Set `findOnPageCountTextView`.
380 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
385 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
386 findOnPageEditText.addTextChangedListener(new TextWatcher() {
388 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
393 public void onTextChanged(CharSequence s, int start, int before, int count) {
398 public void afterTextChanged(Editable s) {
399 // Search for the text in `mainWebView`.
400 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
404 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
405 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
407 public boolean onKey(View v, int keyCode, KeyEvent event) {
408 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
409 // Hide the soft keyboard. `0` indicates no additional flags.
410 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
412 // Consume the event.
414 } else { // A different key was pressed.
415 // Do not consume the event.
421 // Implement swipe to refresh
422 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
423 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
424 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
426 public void onRefresh() {
427 mainWebView.reload();
431 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
432 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
434 // Listen for touches on the navigation menu.
435 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
436 navigationView.setNavigationItemSelectedListener(this);
438 // 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.
439 final Menu navigationMenu = navigationView.getMenu();
440 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
441 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
442 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
444 // The `DrawerListener` allows us to update the Navigation Menu.
445 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
447 public void onDrawerSlide(View drawerView, float slideOffset) {
451 public void onDrawerOpened(View drawerView) {
455 public void onDrawerClosed(View drawerView) {
459 public void onDrawerStateChanged(int newState) {
460 // Update the `Back`, `Forward`, and `History` menu items every time the drawer opens.
461 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
462 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
463 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
465 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
466 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
470 // drawerToggle creates the hamburger icon at the start of the AppBar.
471 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
473 // Initialize `adServerSet`.
474 final Set<String> adServersSet = new HashSet<>();
476 // Load the list of ad servers into memory.
478 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
479 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
481 // Create a string for storing each ad server.
484 // Populate `adServersSet`.
485 while ((adServer = bufferedReader.readLine()) != null) {
486 adServersSet.add(adServer);
489 // Close `bufferedReader`.
490 bufferedReader.close();
491 } catch (IOException ioException) {
492 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
495 mainWebView.setWebViewClient(new WebViewClient() {
496 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
497 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
498 @SuppressWarnings("deprecation")
500 public boolean shouldOverrideUrlLoading(WebView view, String url) {
501 // Use an external email program if the link begins with `mailto:`.
502 if (url.startsWith("mailto:")) {
503 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
504 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
506 // Parse the url and set it as the data for the `Intent`.
507 emailIntent.setData(Uri.parse(url));
509 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
510 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
513 startActivity(emailIntent);
515 } else { // Load the URL in Privacy Browser.
516 mainWebView.loadUrl(url, customHeaders);
521 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
522 @SuppressWarnings("deprecation")
524 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
525 if (adBlockerEnabled) { // Block ads.
526 // Extract the host from `url`.
527 Uri requestUri = Uri.parse(url);
528 String requestHost = requestUri.getHost();
530 // Create a variable to track if this is an ad server.
531 boolean requestHostIsAdServer = false;
533 // Check all the subdomains of `requestHost` if it is not `null`.
534 if (requestHost != null) {
535 while (requestHost.contains(".")) {
536 if (adServersSet.contains(requestHost)) {
537 requestHostIsAdServer = true;
540 // Strip out the lowest subdomain of `requestHost`.
541 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
545 if (requestHostIsAdServer) { // It is an ad server.
546 // Return an empty `WebResourceResponse`.
547 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
548 } else { // It is not an ad server.
549 // `return null` loads the requested resource.
552 } else { // Ad blocking is disabled.
553 // `return null` loads the requested resource.
558 // Update the URL in urlTextBox when the page starts to load.
560 public void onPageStarted(WebView view, String url, Bitmap favicon) {
561 // 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.
562 formattedUrlString = url;
564 // Display the loading URL is the URL text box.
565 urlTextBox.setText(url);
568 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
570 public void onPageFinished(WebView view, String url) {
571 formattedUrlString = url;
573 // Only update urlTextBox if the user is not typing in it.
574 if (!urlTextBox.hasFocus()) {
575 urlTextBox.setText(formattedUrlString);
578 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
579 sslCertificate = mainWebView.getCertificate();
582 // Handle SSL Certificate errors.
584 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
585 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
586 sslErrorHandler = handler;
588 // Display the SSL error `AlertDialog`.
589 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
590 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
594 mainWebView.setWebChromeClient(new WebChromeClient() {
595 // Update the progress bar when a page is loading.
597 public void onProgressChanged(WebView view, int progress) {
598 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
599 progressBar.setProgress(progress);
600 if (progress < 100) {
601 progressBar.setVisibility(View.VISIBLE);
603 progressBar.setVisibility(View.GONE);
605 //Stop the `SwipeToRefresh` indicator if it is running
606 swipeRefreshLayout.setRefreshing(false);
610 // Set the favorite icon when it changes.
612 public void onReceivedIcon(WebView view, Bitmap icon) {
613 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
616 // Place the favorite icon in the appBar.
617 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
618 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
621 // Enter full screen video
623 public void onShowCustomView(View view, CustomViewCallback callback) {
624 // Pause the ad if this is the free flavor.
625 if (BuildConfig.FLAVOR.contentEquals("free")) {
626 BannerAd.pauseAd(adView);
629 // Remove the translucent overlays.
630 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
632 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
633 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
635 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
636 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
637 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
639 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
641 // Set `rootCoordinatorLayout` to fill the entire screen.
642 rootCoordinatorLayout.setFitsSystemWindows(false);
644 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
645 fullScreenVideoFrameLayout.addView(view);
646 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
649 // Exit full screen video
650 public void onHideCustomView() {
651 // Hide `fullScreenVideoFrameLayout`.
652 fullScreenVideoFrameLayout.removeAllViews();
653 fullScreenVideoFrameLayout.setVisibility(View.GONE);
655 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
656 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
658 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
659 rootCoordinatorLayout.setFitsSystemWindows(true);
661 // Show the ad if this is the free flavor.
662 if (BuildConfig.FLAVOR.contentEquals("free")) {
663 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
664 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
666 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
667 adView = findViewById(R.id.adView);
672 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
673 registerForContextMenu(mainWebView);
675 // Allow the downloading of files.
676 mainWebView.setDownloadListener(new DownloadListener() {
678 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
679 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
680 AppCompatDialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
681 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
685 // Allow pinch to zoom.
686 mainWebView.getSettings().setBuiltInZoomControls(true);
688 // Hide zoom controls.
689 mainWebView.getSettings().setDisplayZoomControls(false);
691 // Initialize cookieManager.
692 cookieManager = CookieManager.getInstance();
694 // 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).
695 customHeaders.put("X-Requested-With", "");
697 // 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.
698 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
700 // Apply the settings from the shared preferences.
703 // Get the intent information that started the app.
704 final Intent intent = getIntent();
706 if (intent.getData() != null) {
707 // Get the intent data and convert it to a string.
708 final Uri intentUriData = intent.getData();
709 formattedUrlString = intentUriData.toString();
712 // If formattedUrlString is null assign the homepage to it.
713 if (formattedUrlString == null) {
714 formattedUrlString = homepage;
717 // Load the initial website.
718 mainWebView.loadUrl(formattedUrlString, customHeaders);
720 // If the favorite icon is null, load the default.
721 if (favoriteIcon == null) {
722 // We have to use `ContextCompat` until API >= 21.
723 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
724 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
725 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
728 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
729 inFullScreenBrowsingMode = false;
731 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
732 adView = findViewById(R.id.adView);
733 BannerAd.requestAd(adView);
738 protected void onNewIntent(Intent intent) {
739 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
742 if (intent.getData() != null) {
743 // Get the intent data and convert it to a string.
744 final Uri intentUriData = intent.getData();
745 formattedUrlString = intentUriData.toString();
748 // Close the navigation drawer if it is open.
749 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
750 drawerLayout.closeDrawer(GravityCompat.START);
754 mainWebView.loadUrl(formattedUrlString, customHeaders);
756 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
757 mainWebView.requestFocus();
761 public boolean onCreateOptionsMenu(Menu menu) {
762 // Inflate the menu; this adds items to the action bar if it is present.
763 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
765 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
768 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
769 updatePrivacyIcons(false);
771 // Get handles for the menu items.
772 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
773 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
774 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
775 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
777 // Only display third-Party Cookies if SDK >= 21
778 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
780 // Get the shared preference values. `this` references the current context.
781 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
783 // Set the status of the additional app bar icons. The default is `false`.
784 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
785 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
786 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
787 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
788 } else { //Do not display the additional icons.
789 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
790 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
791 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
798 public boolean onPrepareOptionsMenu(Menu menu) {
799 // Get handles for the menu items.
800 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
801 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
802 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
803 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
804 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
805 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
806 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
808 // Set the status of the menu item checkboxes.
809 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
810 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
811 toggleDomStorage.setChecked(domStorageEnabled);
812 toggleSaveFormData.setChecked(saveFormDataEnabled);
814 // Enable third-party cookies if first-party cookies are enabled.
815 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
817 // Enable DOM Storage if JavaScript is enabled.
818 toggleDomStorage.setEnabled(javaScriptEnabled);
820 // Enable Clear Cookies if there are any.
821 clearCookies.setEnabled(cookieManager.hasCookies());
823 // Enable Clear Form Data is there is any.
824 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
825 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
827 // Only show `Refresh` if `swipeToRefresh` is disabled.
828 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
830 // Initialize font size variables.
831 int fontSize = mainWebView.getSettings().getTextZoom();
832 String fontSizeTitle;
833 MenuItem selectedFontSizeMenuItem;
835 // Prepare the font size title and current size menu item.
838 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
839 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
843 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
844 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
848 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
849 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
853 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
854 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
858 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
859 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
863 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
864 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
868 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
869 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
873 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
874 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
878 // Set the font size title and select the current size menu item.
879 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
880 fontSizeMenuItem.setTitle(fontSizeTitle);
881 selectedFontSizeMenuItem.setChecked(true);
883 // Run all the other default commands.
884 super.onPrepareOptionsMenu(menu);
886 // `return true` displays the menu.
891 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
892 @SuppressLint("SetJavaScriptEnabled")
893 // removeAllCookies is deprecated, but it is required for API < 21.
894 @SuppressWarnings("deprecation")
895 public boolean onOptionsItemSelected(MenuItem menuItem) {
896 int menuItemId = menuItem.getItemId();
898 // Set the commands that relate to the menu entries.
899 switch (menuItemId) {
900 case R.id.toggleJavaScript:
901 // Switch the status of javaScriptEnabled.
902 javaScriptEnabled = !javaScriptEnabled;
904 // Apply the new JavaScript status.
905 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
907 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
908 updatePrivacyIcons(true);
910 // Display a `Snackbar`.
911 if (javaScriptEnabled) { // JavaScrip is enabled.
912 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
913 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
914 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
915 } else { // Privacy mode.
916 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
919 // Reload the WebView.
920 mainWebView.reload();
923 case R.id.toggleFirstPartyCookies:
924 // Switch the status of firstPartyCookiesEnabled.
925 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
927 // Update the menu checkbox.
928 menuItem.setChecked(firstPartyCookiesEnabled);
930 // Apply the new cookie status.
931 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
933 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
934 updatePrivacyIcons(true);
936 // Display a `Snackbar`.
937 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
938 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
939 } else if (javaScriptEnabled){ // JavaScript is still enabled.
940 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
941 } else { // Privacy mode.
942 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
945 // Reload the WebView.
946 mainWebView.reload();
949 case R.id.toggleThirdPartyCookies:
950 if (Build.VERSION.SDK_INT >= 21) {
951 // Switch the status of thirdPartyCookiesEnabled.
952 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
954 // Update the menu checkbox.
955 menuItem.setChecked(thirdPartyCookiesEnabled);
957 // Apply the new cookie status.
958 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
960 // Display a `Snackbar`.
961 if (thirdPartyCookiesEnabled) {
962 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
964 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
967 // Reload the WebView.
968 mainWebView.reload();
969 } // Else do nothing because SDK < 21.
972 case R.id.toggleDomStorage:
973 // Switch the status of domStorageEnabled.
974 domStorageEnabled = !domStorageEnabled;
976 // Update the menu checkbox.
977 menuItem.setChecked(domStorageEnabled);
979 // Apply the new DOM Storage status.
980 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
982 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
983 updatePrivacyIcons(true);
985 // Display a `Snackbar`.
986 if (domStorageEnabled) {
987 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
989 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
992 // Reload the WebView.
993 mainWebView.reload();
996 case R.id.toggleSaveFormData:
997 // Switch the status of saveFormDataEnabled.
998 saveFormDataEnabled = !saveFormDataEnabled;
1000 // Update the menu checkbox.
1001 menuItem.setChecked(saveFormDataEnabled);
1003 // Apply the new form data status.
1004 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1006 // Display a `Snackbar`.
1007 if (saveFormDataEnabled) {
1008 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1010 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1013 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1014 updatePrivacyIcons(true);
1016 // Reload the WebView.
1017 mainWebView.reload();
1020 case R.id.clearCookies:
1021 if (Build.VERSION.SDK_INT < 21) {
1022 cookieManager.removeAllCookie();
1024 cookieManager.removeAllCookies(null);
1026 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1029 case R.id.clearDomStorage:
1030 WebStorage webStorage = WebStorage.getInstance();
1031 webStorage.deleteAllData();
1032 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1035 case R.id.clearFormData:
1036 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1037 mainWebViewDatabase.clearFormData();
1038 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1041 case R.id.fontSizeFiftyPercent:
1042 mainWebView.getSettings().setTextZoom(50);
1045 case R.id.fontSizeSeventyFivePercent:
1046 mainWebView.getSettings().setTextZoom(75);
1049 case R.id.fontSizeOneHundredPercent:
1050 mainWebView.getSettings().setTextZoom(100);
1053 case R.id.fontSizeOneHundredTwentyFivePercent:
1054 mainWebView.getSettings().setTextZoom(125);
1057 case R.id.fontSizeOneHundredFiftyPercent:
1058 mainWebView.getSettings().setTextZoom(150);
1061 case R.id.fontSizeOneHundredSeventyFivePercent:
1062 mainWebView.getSettings().setTextZoom(175);
1065 case R.id.fontSizeTwoHundredPercent:
1066 mainWebView.getSettings().setTextZoom(200);
1069 case R.id.find_on_page:
1070 // Hide the URL app bar.
1071 supportAppBar.setVisibility(View.GONE);
1073 // Show the Find on Page `RelativeLayout`.
1074 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1076 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1077 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1078 findOnPageEditText.postDelayed(new Runnable()
1083 // Set the focus on `findOnPageEditText`.
1084 findOnPageEditText.requestFocus();
1086 // Display the keyboard.
1087 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1093 Intent shareIntent = new Intent();
1094 shareIntent.setAction(Intent.ACTION_SEND);
1095 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1096 shareIntent.setType("text/plain");
1097 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1100 case R.id.addToHomescreen:
1101 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `R.string.create_shortcut`.
1102 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
1103 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1105 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
1109 // Get a `PrintManager` instance.
1110 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1112 // Convert `mainWebView` to `printDocumentAdapter`.
1113 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1115 // Print the document. The print attributes are `null`.
1116 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1120 mainWebView.reload();
1124 // Don't consume the event.
1125 return super.onOptionsItemSelected(menuItem);
1129 // removeAllCookies is deprecated, but it is required for API < 21.
1130 @SuppressWarnings("deprecation")
1132 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1133 int menuItemId = menuItem.getItemId();
1135 switch (menuItemId) {
1137 mainWebView.loadUrl(homepage, customHeaders);
1141 if (mainWebView.canGoBack()) {
1142 mainWebView.goBack();
1147 if (mainWebView.canGoForward()) {
1148 mainWebView.goForward();
1153 // Gte the `WebBackForwardList`.
1154 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1156 // Show the `UrlHistory` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1157 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistory.loadBackForwardList(this, webBackForwardList);
1158 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1161 case R.id.bookmarks:
1162 // Launch Bookmarks.
1163 Intent bookmarksIntent = new Intent(this, Bookmarks.class);
1164 startActivity(bookmarksIntent);
1167 case R.id.downloads:
1168 // Launch the system Download Manager.
1169 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1171 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1172 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1174 startActivity(downloadManagerIntent);
1178 // Launch `Settings`.
1179 Intent settingsIntent = new Intent(this, Settings.class);
1180 startActivity(settingsIntent);
1185 Intent guideIntent = new Intent(this, Guide.class);
1186 startActivity(guideIntent);
1191 Intent aboutIntent = new Intent(this, About.class);
1192 startActivity(aboutIntent);
1195 case R.id.clearAndExit:
1196 // Clear cookies. The commands changed slightly in API 21.
1197 if (Build.VERSION.SDK_INT >= 21) {
1198 cookieManager.removeAllCookies(null);
1200 cookieManager.removeAllCookie();
1203 // Clear DOM storage.
1204 WebStorage domStorage = WebStorage.getInstance();
1205 domStorage.deleteAllData();
1208 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1209 webViewDatabase.clearFormData();
1211 // Clear cache. The argument of "true" includes disk files.
1212 mainWebView.clearCache(true);
1214 // Clear the back/forward history.
1215 mainWebView.clearHistory();
1217 // Clear any SSL certificate preferences.
1218 mainWebView.clearSslPreferences();
1220 // Clear `formattedUrlString`.
1221 formattedUrlString = null;
1223 // Clear `customHeaders`.
1224 customHeaders.clear();
1226 // Detach all views from `mainWebViewRelativeLayout`.
1227 mainWebViewRelativeLayout.removeAllViews();
1229 // Destroy the internal state of `mainWebView`.
1230 mainWebView.destroy();
1232 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1233 if (Build.VERSION.SDK_INT >= 21) {
1234 finishAndRemoveTask();
1239 // Remove the terminated program from RAM. The status code is `0`.
1247 // Close the navigation drawer.
1248 drawerLayout.closeDrawer(GravityCompat.START);
1253 public void onPostCreate(Bundle savedInstanceState) {
1254 super.onPostCreate(savedInstanceState);
1256 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1257 drawerToggle.syncState();
1261 public void onConfigurationChanged(Configuration newConfig) {
1262 super.onConfigurationChanged(newConfig);
1264 // Reload the ad for the free flavor if we are not in full screen mode.
1265 if (BuildConfig.FLAVOR.contentEquals("free") && adView.isShown() && !fullScreenVideoFrameLayout.isShown()) {
1267 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1269 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1270 adView = findViewById(R.id.adView);
1273 // `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
1274 // ActivityCompat.invalidateOptionsMenu(this);
1278 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1279 // Store the `HitTestResult`.
1280 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1283 final String imageUrl;
1284 final String linkUrl;
1286 // Get a handle for the `ClipboardManager`.
1287 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1289 switch (hitTestResult.getType()) {
1290 // `SRC_ANCHOR_TYPE` is a link.
1291 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1292 // Get the target URL.
1293 linkUrl = hitTestResult.getExtra();
1295 // Set the target URL as the title of the `ContextMenu`.
1296 menu.setHeaderTitle(linkUrl);
1298 // Add a `Load URL` entry.
1299 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1301 public boolean onMenuItemClick(MenuItem item) {
1302 mainWebView.loadUrl(linkUrl, customHeaders);
1307 // Add a `Copy URL` entry.
1308 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1310 public boolean onMenuItemClick(MenuItem item) {
1311 // Save the link URL in a `ClipData`.
1312 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1314 // Set the `ClipData` as the clipboard's primary clip.
1315 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1320 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1321 menu.add(R.string.cancel);
1324 case WebView.HitTestResult.EMAIL_TYPE:
1325 // Get the target URL.
1326 linkUrl = hitTestResult.getExtra();
1328 // Set the target URL as the title of the `ContextMenu`.
1329 menu.setHeaderTitle(linkUrl);
1331 // Add a `Write Email` entry.
1332 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1334 public boolean onMenuItemClick(MenuItem item) {
1335 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1336 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1338 // Parse the url and set it as the data for the `Intent`.
1339 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1341 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1342 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1345 startActivity(emailIntent);
1350 // Add a `Copy Email Address` entry.
1351 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1353 public boolean onMenuItemClick(MenuItem item) {
1354 // Save the email address in a `ClipData`.
1355 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1357 // Set the `ClipData` as the clipboard's primary clip.
1358 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1363 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1364 menu.add(R.string.cancel);
1367 // `IMAGE_TYPE` is an image.
1368 case WebView.HitTestResult.IMAGE_TYPE:
1369 // Get the image URL.
1370 imageUrl = hitTestResult.getExtra();
1372 // Set the image URL as the title of the `ContextMenu`.
1373 menu.setHeaderTitle(imageUrl);
1375 // Add a `View Image` entry.
1376 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1378 public boolean onMenuItemClick(MenuItem item) {
1379 mainWebView.loadUrl(imageUrl, customHeaders);
1384 // Add a `Download Image` entry.
1385 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1387 public boolean onMenuItemClick(MenuItem item) {
1388 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1389 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1390 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1395 // Add a `Copy URL` entry.
1396 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1398 public boolean onMenuItemClick(MenuItem item) {
1399 // Save the image URL in a `ClipData`.
1400 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1402 // Set the `ClipData` as the clipboard's primary clip.
1403 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1408 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1409 menu.add(R.string.cancel);
1413 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1414 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1415 // Get the image URL.
1416 imageUrl = hitTestResult.getExtra();
1418 // Set the image URL as the title of the `ContextMenu`.
1419 menu.setHeaderTitle(imageUrl);
1421 // Add a `View Image` entry.
1422 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1424 public boolean onMenuItemClick(MenuItem item) {
1425 mainWebView.loadUrl(imageUrl, customHeaders);
1430 // Add a `Download Image` entry.
1431 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1433 public boolean onMenuItemClick(MenuItem item) {
1434 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1435 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1436 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1441 // Add a `Copy URL` entry.
1442 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1444 public boolean onMenuItemClick(MenuItem item) {
1445 // Save the image URL in a `ClipData`.
1446 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1448 // Set the `ClipData` as the clipboard's primary clip.
1449 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1454 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1455 menu.add(R.string.cancel);
1461 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1462 // Get shortcutNameEditText from the alert dialog.
1463 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1465 // Create the bookmark shortcut based on formattedUrlString.
1466 Intent bookmarkShortcut = new Intent();
1467 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1468 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1470 // Place the bookmark shortcut on the home screen.
1471 Intent placeBookmarkShortcut = new Intent();
1472 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1473 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1474 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1475 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1476 sendBroadcast(placeBookmarkShortcut);
1480 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1481 // Download the image if it has an HTTP or HTTPS URI.
1482 if (imageUrl.startsWith("http")) {
1483 // Get a handle for the system `DOWNLOAD_SERVICE`.
1484 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1486 // Parse `imageUrl`.
1487 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1489 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1490 if (firstPartyCookiesEnabled) {
1491 // Get the cookies for `imageUrl`.
1492 String cookies = cookieManager.getCookie(imageUrl);
1494 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1495 downloadRequest.addRequestHeader("Cookie", cookies);
1498 // Get the file name from `dialogFragment`.
1499 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1500 String imageName = downloadImageNameEditText.getText().toString();
1502 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1503 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1504 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1505 } else { // Only set the title using `imageName`.
1506 downloadRequest.setTitle(imageName);
1509 // Allow `MediaScanner` to index the download if it is a media file.
1510 downloadRequest.allowScanningByMediaScanner();
1512 // Add the URL as the description for the download.
1513 downloadRequest.setDescription(imageUrl);
1515 // Show the download notification after the download is completed.
1516 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1518 // Initiate the download.
1519 downloadManager.enqueue(downloadRequest);
1520 } else { // The image is not an HTTP or HTTPS URI.
1521 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1526 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1527 // Download the file if it has an HTTP or HTTPS URI.
1528 if (downloadUrl.startsWith("http")) {
1530 // Get a handle for the system `DOWNLOAD_SERVICE`.
1531 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1533 // Parse `downloadUrl`.
1534 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1536 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
1537 if (firstPartyCookiesEnabled) {
1538 // Get the cookies for `downloadUrl`.
1539 String cookies = cookieManager.getCookie(downloadUrl);
1541 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1542 downloadRequest.addRequestHeader("Cookie", cookies);
1545 // Get the file name from `dialogFragment`.
1546 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1547 String fileName = downloadFileNameEditText.getText().toString();
1549 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1550 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1551 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1552 } else { // Only set the title using `fileName`.
1553 downloadRequest.setTitle(fileName);
1556 // Allow `MediaScanner` to index the download if it is a media file.
1557 downloadRequest.allowScanningByMediaScanner();
1559 // Add the URL as the description for the download.
1560 downloadRequest.setDescription(downloadUrl);
1562 // Show the download notification after the download is completed.
1563 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1565 // Initiate the download.
1566 downloadManager.enqueue(downloadRequest);
1567 } else { // The download is not an HTTP or HTTPS URI.
1568 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1572 public void viewSslCertificate(View view) {
1573 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1574 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1575 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1579 public void onSslErrorCancel() {
1580 sslErrorHandler.cancel();
1584 public void onSslErrorProceed() {
1585 sslErrorHandler.proceed();
1589 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1590 // Load the history entry.
1591 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1595 public void onClearHistory() {
1596 // Clear the history.
1597 mainWebView.clearHistory();
1600 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1602 public void onBackPressed() {
1603 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1604 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1605 drawerLayout.closeDrawer(GravityCompat.START);
1607 // Load the previous URL if available.
1608 if (mainWebView.canGoBack()) {
1609 mainWebView.goBack();
1611 // Pass `onBackPressed()` to the system.
1612 super.onBackPressed();
1618 public void onPause() {
1619 // Pause `mainWebView`.
1620 mainWebView.onPause();
1622 // Stop all JavaScript.
1623 mainWebView.pauseTimers();
1625 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1626 if (BuildConfig.FLAVOR.contentEquals("free")) {
1627 BannerAd.pauseAd(adView);
1634 public void onResume() {
1637 // Resume JavaScript (if enabled).
1638 mainWebView.resumeTimers();
1640 // Resume `mainWebView`.
1641 mainWebView.onResume();
1643 // Resume the adView for the free flavor.
1644 if (BuildConfig.FLAVOR.contentEquals("free")) {
1645 BannerAd.resumeAd(adView);
1650 public void onRestart() {
1653 // Apply the settings from shared preferences, which might have been changed in `Settings`.
1656 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1657 updatePrivacyIcons(true);
1661 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1662 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1663 String unformattedUrlString = urlTextBox.getText().toString().trim();
1665 URL unformattedUrl = null;
1666 Uri.Builder formattedUri = new Uri.Builder();
1668 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1669 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1670 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1671 if (!unformattedUrlString.startsWith("http")) {
1672 unformattedUrlString = "http://" + unformattedUrlString;
1675 // 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.
1677 unformattedUrl = new URL(unformattedUrlString);
1678 } catch (MalformedURLException e) {
1679 e.printStackTrace();
1682 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1683 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1684 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1685 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1686 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1687 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1689 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1690 formattedUrlString = formattedUri.build().toString();
1692 // Sanitize the search input and convert it to a DuckDuckGo search.
1693 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1695 // Use the correct search URL.
1696 if (javaScriptEnabled) { // JavaScript is enabled.
1697 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1698 } else { // JavaScript is disabled.
1699 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1703 mainWebView.loadUrl(formattedUrlString, customHeaders);
1705 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1706 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1709 public void findPreviousOnPage(View view) {
1710 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
1711 mainWebView.findNext(false);
1714 public void findNextOnPage(View view) {
1715 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
1716 mainWebView.findNext(true);
1719 public void closeFindOnPage(View view) {
1720 // Delete the contents of `find_on_page_edittext`.
1721 findOnPageEditText.setText(null);
1723 // Clear the highlighted phrases.
1724 mainWebView.clearMatches();
1726 // Hide the Find on Page `RelativeLayout`.
1727 findOnPageLinearLayout.setVisibility(View.GONE);
1729 // Show the URL app bar.
1730 supportAppBar.setVisibility(View.VISIBLE);
1732 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1733 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1736 private void applySettings() {
1737 // Get the shared preference values. `this` references the current context.
1738 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1740 // Store the values from `sharedPreferences` in variables.
1741 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
1742 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1743 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1744 String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1745 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1746 String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1747 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1748 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1749 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1750 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
1751 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
1752 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1753 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
1754 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
1755 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
1757 // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1758 if (javaScriptEnabled == null) { // If `javaScriptEnabled` is null the program is just starting.
1759 // Get the values from `sharedPreferences`.
1760 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1761 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1762 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1763 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1764 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1766 // Apply the default settings.
1767 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1768 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1769 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1770 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1771 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1773 // Set third-party cookies status if API >= 21.
1774 if (Build.VERSION.SDK_INT >= 21) {
1775 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1779 // Apply the other settings from `sharedPreferences`.
1780 homepage = homepageString;
1781 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1783 // Set the user agent initial status.
1784 switch (userAgentString) {
1785 case "Default user agent":
1786 // Set the user agent to `""`, which uses the default value.
1787 mainWebView.getSettings().setUserAgentString("");
1790 case "Custom user agent":
1791 // Set the custom user agent.
1792 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1796 // Use the selected user agent.
1797 mainWebView.getSettings().setUserAgentString(userAgentString);
1801 // Set JavaScript disabled search.
1802 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1803 javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1804 } else { // Use the string from the pre-built list.
1805 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1808 // Set JavaScript enabled search.
1809 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1810 javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1811 } else { // Use the string from the pre-built list.
1812 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1815 // Set Do Not Track status.
1816 if (doNotTrackEnabled) {
1817 customHeaders.put("DNT", "1");
1819 customHeaders.remove("DNT");
1822 // Set Orbot proxy status.
1823 if (proxyThroughOrbot) {
1824 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
1825 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1826 } else { // Reset the proxy to default. The host is `""` and the port is `"0"`.
1827 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1830 // If we are in full screen mode update the `SYSTEM_UI` flags.
1831 if (inFullScreenBrowsingMode) {
1832 if (hideSystemBarsOnFullscreen) { // Hide everything.
1833 // Remove the translucent navigation setting if it is currently flagged.
1834 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1836 // Remove the translucent status bar overlay.
1837 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1839 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1840 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1842 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1843 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1844 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1846 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1847 } else { // Hide everything except the status and navigation bars.
1848 // Add the translucent status flag if it is unset.
1849 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1851 if (translucentNavigationBarOnFullscreen) {
1852 // Set the navigation bar to be translucent.
1853 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1855 // Set the navigation bar to be black.
1856 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1862 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
1863 // Get handles for the icons.
1864 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1865 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1866 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1867 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1869 // Update `privacyIcon`.
1870 if (javaScriptEnabled) { // JavaScript is enabled.
1871 privacyIcon.setIcon(R.drawable.javascript_enabled);
1872 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1873 privacyIcon.setIcon(R.drawable.warning);
1874 } else { // All the dangerous features are disabled.
1875 privacyIcon.setIcon(R.drawable.privacy_mode);
1878 // Update `firstPartyCookiesIcon`.
1879 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1880 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1881 } else { // First-party cookies are disabled.
1882 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1885 // Update `domStorageIcon`.
1886 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
1887 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1888 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
1889 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1890 } else { // JavaScript is disabled, so DOM storage is ghosted.
1891 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1894 // Update `formDataIcon`.
1895 if (saveFormDataEnabled) { // Form data is enabled.
1896 formDataIcon.setIcon(R.drawable.form_data_enabled);
1897 } else { // Form data is disabled.
1898 formDataIcon.setIcon(R.drawable.form_data_disabled);
1901 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
1902 if (runInvalidateOptionsMenu) {
1903 ActivityCompat.invalidateOptionsMenu(this);