2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
6 * Privacy Browser is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * Privacy Browser is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
20 package com.stoutner.privacybrowser.activities;
22 import android.annotation.SuppressLint;
23 import android.app.DialogFragment;
24 import android.app.DownloadManager;
25 import android.content.ClipData;
26 import android.content.ClipboardManager;
27 import android.content.Context;
28 import android.content.Intent;
29 import android.content.SharedPreferences;
30 import android.content.res.Configuration;
31 import android.graphics.Bitmap;
32 import android.graphics.drawable.BitmapDrawable;
33 import android.graphics.drawable.Drawable;
34 import android.net.Uri;
35 import android.net.http.SslCertificate;
36 import android.net.http.SslError;
37 import android.os.Build;
38 import android.os.Bundle;
39 import android.preference.PreferenceManager;
40 import android.print.PrintDocumentAdapter;
41 import android.print.PrintManager;
42 import android.support.annotation.NonNull;
43 import android.support.design.widget.CoordinatorLayout;
44 import android.support.design.widget.NavigationView;
45 import android.support.design.widget.Snackbar;
46 import android.support.v4.app.ActivityCompat;
47 import android.support.v4.content.ContextCompat;
48 import android.support.v4.view.GravityCompat;
49 import android.support.v4.widget.DrawerLayout;
50 import android.support.v4.widget.SwipeRefreshLayout;
51 import android.support.v7.app.ActionBar;
52 import android.support.v7.app.ActionBarDrawerToggle;
53 import android.support.v7.app.AppCompatActivity;
54 import android.support.v7.app.AppCompatDialogFragment;
55 import android.support.v7.widget.Toolbar;
56 import android.text.Editable;
57 import android.text.TextWatcher;
58 import android.util.Patterns;
59 import android.view.ContextMenu;
60 import android.view.GestureDetector;
61 import android.view.KeyEvent;
62 import android.view.Menu;
63 import android.view.MenuItem;
64 import android.view.MotionEvent;
65 import android.view.View;
66 import android.view.WindowManager;
67 import android.view.inputmethod.InputMethodManager;
68 import android.webkit.CookieManager;
69 import android.webkit.DownloadListener;
70 import android.webkit.SslErrorHandler;
71 import android.webkit.WebBackForwardList;
72 import android.webkit.WebChromeClient;
73 import android.webkit.WebResourceResponse;
74 import android.webkit.WebStorage;
75 import android.webkit.WebView;
76 import android.webkit.WebViewClient;
77 import android.webkit.WebViewDatabase;
78 import android.widget.EditText;
79 import android.widget.FrameLayout;
80 import android.widget.ImageView;
81 import android.widget.LinearLayout;
82 import android.widget.ProgressBar;
83 import android.widget.RelativeLayout;
84 import android.widget.TextView;
86 import com.stoutner.privacybrowser.BannerAd;
87 import com.stoutner.privacybrowser.BuildConfig;
88 import com.stoutner.privacybrowser.R;
89 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
90 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcut;
91 import com.stoutner.privacybrowser.dialogs.DownloadFile;
92 import com.stoutner.privacybrowser.dialogs.DownloadImage;
93 import com.stoutner.privacybrowser.dialogs.SslCertificateError;
94 import com.stoutner.privacybrowser.dialogs.UrlHistory;
95 import com.stoutner.privacybrowser.dialogs.ViewSslCertificate;
97 import java.io.BufferedReader;
98 import java.io.ByteArrayInputStream;
99 import java.io.IOException;
100 import java.io.InputStreamReader;
101 import java.io.UnsupportedEncodingException;
102 import java.net.MalformedURLException;
104 import java.net.URLEncoder;
105 import java.util.HashMap;
106 import java.util.HashSet;
107 import java.util.Map;
108 import java.util.Set;
110 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
111 public class MainWebView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
112 SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener, DownloadImage.DownloadImageListener, UrlHistory.UrlHistoryListener {
114 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
115 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applySettings()`.
116 public static ActionBar appBar;
118 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `Bookmarks`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
119 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
120 public static Bitmap favoriteIcon;
122 // `formattedUrlString` is public static so it can be accessed from `Bookmarks`.
123 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
124 public static String formattedUrlString;
126 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`. It is also used in `onCreate()`.
127 public static SslCertificate sslCertificate;
131 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
132 private DrawerLayout drawerLayout;
134 // `rootCoordinatorLayout` is used in `onCreate()` and `applySettings()`.
135 private CoordinatorLayout rootCoordinatorLayout;
137 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
138 private WebView mainWebView;
140 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
141 private FrameLayout fullScreenVideoFrameLayout;
143 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
144 private SwipeRefreshLayout swipeRefreshLayout;
146 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, and `onRestart()`.
147 private CookieManager cookieManager;
149 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrlFromTextBox()`.
150 private final Map<String, String> customHeaders = new HashMap<>();
152 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
153 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
154 private Boolean javaScriptEnabled;
156 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
157 private boolean firstPartyCookiesEnabled;
159 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
160 private boolean thirdPartyCookiesEnabled;
162 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
163 private boolean domStorageEnabled;
165 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
166 private boolean saveFormDataEnabled;
168 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
169 private boolean swipeToRefreshEnabled;
171 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
172 private String homepage;
174 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
175 private String javaScriptDisabledSearchURL;
177 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
178 private String javaScriptEnabledSearchURL;
180 // `adBlockerEnabled` is used in `onCreate()` and `applySettings()`.
181 private boolean adBlockerEnabled;
183 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applySettings()`.
184 private boolean fullScreenBrowsingModeEnabled;
186 // `inFullScreenBrowsingMode` is used in `onCreate()` and `applySettings()`.
187 private boolean inFullScreenBrowsingMode;
189 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
190 private boolean hideSystemBarsOnFullscreen;
192 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
193 private boolean translucentNavigationBarOnFullscreen;
195 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
196 private LinearLayout findOnPageLinearLayout;
198 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
199 private EditText findOnPageEditText;
201 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
202 private Menu mainMenu;
204 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
205 private ActionBarDrawerToggle drawerToggle;
207 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
208 private Toolbar supportAppBar;
210 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
211 private EditText urlTextBox;
213 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
216 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
217 private SslErrorHandler sslErrorHandler;
219 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
220 private InputMethodManager inputMethodManager;
222 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
223 private RelativeLayout mainWebViewRelativeLayout;
226 // 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.
227 @SuppressLint("SetJavaScriptEnabled")
228 protected void onCreate(Bundle savedInstanceState) {
229 super.onCreate(savedInstanceState);
230 setContentView(R.layout.drawerlayout);
232 // Get a handle for `inputMethodManager`.
233 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
235 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
236 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
237 setSupportActionBar(supportAppBar);
238 appBar = getSupportActionBar();
240 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
241 assert appBar != null;
243 // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
244 appBar.setCustomView(R.layout.url_app_bar);
245 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
247 // Set the "go" button on the keyboard to load the URL in urlTextBox.
248 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
249 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
251 public boolean onKey(View v, int keyCode, KeyEvent event) {
252 // If the event is a key-down event on the `enter` button, load the URL.
253 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
254 // Load the URL into the mainWebView and consume the event.
256 loadUrlFromTextBox();
257 } catch (UnsupportedEncodingException e) {
260 // If the enter key was pressed, consume the event.
263 // If any other key was pressed, do not consume the event.
269 // Get handles for views that need to be accessed.
270 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
271 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
272 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
273 mainWebView = (WebView) findViewById(R.id.mainWebView);
274 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
275 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
276 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
278 // Create a double-tap listener to toggle full-screen mode.
279 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
280 // Override `onDoubleTap()`. All other events are handled using the default settings.
282 public boolean onDoubleTap(MotionEvent event) {
283 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
284 // Toggle `inFullScreenBrowsingMode`.
285 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
287 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
288 // Hide the `appBar`.
291 // Hide the `BannerAd` in the free flavor.
292 if (BuildConfig.FLAVOR.contentEquals("free")) {
293 BannerAd.hideAd(adView);
296 // Modify the system bars.
297 if (hideSystemBarsOnFullscreen) { // Hide everything.
298 // Remove the translucent overlays.
299 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
301 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
302 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
304 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
305 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
306 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
308 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
310 // Set `rootCoordinatorLayout` to fill the whole screen.
311 rootCoordinatorLayout.setFitsSystemWindows(false);
312 } else { // Hide everything except the status and navigation bars.
313 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
314 rootCoordinatorLayout.setFitsSystemWindows(false);
316 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.
317 // Set the navigation bar to be translucent.
318 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
321 } else { // Switch to normal viewing mode.
322 // Show the `appBar`.
325 // Show the `BannerAd` in the free flavor.
326 if (BuildConfig.FLAVOR.contentEquals("free")) {
327 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
328 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
330 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
331 adView = findViewById(R.id.adView);
334 // Remove the translucent navigation bar flag if it is set.
335 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
337 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
338 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
340 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
341 rootCoordinatorLayout.setSystemUiVisibility(0);
343 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
344 rootCoordinatorLayout.setFitsSystemWindows(true);
347 // Consume the double-tap.
349 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
355 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
356 mainWebView.setOnTouchListener(new View.OnTouchListener() {
358 public boolean onTouch(View v, MotionEvent event) {
359 // Send the `event` to `gestureDetector`.
360 return gestureDetector.onTouchEvent(event);
364 // Update `findOnPageCountTextView`.
365 mainWebView.setFindListener(new WebView.FindListener() {
366 // Get a handle for `findOnPageCountTextView`.
367 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
370 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
371 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
372 // Set `findOnPageCountTextView` to `0/0`.
373 findOnPageCountTextView.setText(R.string.zero_of_zero);
374 } else if (isDoneCounting) { // There are matches.
375 // `activeMatchOrdinal` is zero-based.
376 int activeMatch = activeMatchOrdinal + 1;
378 // Set `findOnPageCountTextView`.
379 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
384 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
385 findOnPageEditText.addTextChangedListener(new TextWatcher() {
387 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
392 public void onTextChanged(CharSequence s, int start, int before, int count) {
397 public void afterTextChanged(Editable s) {
398 // Search for the text in `mainWebView`.
399 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
403 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
404 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
406 public boolean onKey(View v, int keyCode, KeyEvent event) {
407 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
408 // Hide the soft keyboard. `0` indicates no additional flags.
409 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
411 // Consume the event.
413 } else { // A different key was pressed.
414 // Do not consume the event.
420 // Implement swipe to refresh
421 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
422 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
423 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
425 public void onRefresh() {
426 mainWebView.reload();
430 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
431 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
433 // Listen for touches on the navigation menu.
434 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
435 navigationView.setNavigationItemSelectedListener(this);
437 // 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.
438 final Menu navigationMenu = navigationView.getMenu();
439 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
440 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
441 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
443 // The `DrawerListener` allows us to update the Navigation Menu.
444 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
446 public void onDrawerSlide(View drawerView, float slideOffset) {
450 public void onDrawerOpened(View drawerView) {
454 public void onDrawerClosed(View drawerView) {
458 public void onDrawerStateChanged(int newState) {
459 // Update the `Back`, `Forward`, and `History` menu items every time the drawer opens.
460 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
461 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
462 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
464 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
465 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
469 // drawerToggle creates the hamburger icon at the start of the AppBar.
470 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
472 // Initialize `adServerSet`.
473 final Set<String> adServersSet = new HashSet<>();
475 // Load the list of ad servers into memory.
477 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
478 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
480 // Create a string for storing each ad server.
483 // Populate `adServersSet`.
484 while ((adServer = bufferedReader.readLine()) != null) {
485 adServersSet.add(adServer);
488 // Close `bufferedReader`.
489 bufferedReader.close();
490 } catch (IOException ioException) {
491 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
494 mainWebView.setWebViewClient(new WebViewClient() {
495 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
496 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
497 @SuppressWarnings("deprecation")
499 public boolean shouldOverrideUrlLoading(WebView view, String url) {
500 // Use an external email program if the link begins with `mailto:`.
501 if (url.startsWith("mailto:")) {
502 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
503 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
505 // Parse the url and set it as the data for the `Intent`.
506 emailIntent.setData(Uri.parse(url));
508 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
509 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
512 startActivity(emailIntent);
514 } else { // Load the URL in Privacy Browser.
515 mainWebView.loadUrl(url, customHeaders);
520 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
521 @SuppressWarnings("deprecation")
523 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
524 if (adBlockerEnabled) { // Block ads.
525 // Extract the host from `url`.
526 Uri requestUri = Uri.parse(url);
527 String requestHost = requestUri.getHost();
529 // Create a variable to track if this is an ad server.
530 boolean requestHostIsAdServer = false;
532 // Check all the subdomains of `requestHost`.
533 while (requestHost.contains(".")) {
534 if (adServersSet.contains(requestHost)) {
535 requestHostIsAdServer = true;
538 // Strip out the lowest subdomain of `requestHost`.
539 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
542 if (requestHostIsAdServer) { // It is an ad server.
543 // Return an empty `WebResourceResponse`.
544 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
545 } else { // It is not an ad server.
546 // `return null` loads the requested resource.
549 } else { // Ad blocking is disabled.
550 // `return null` loads the requested resource.
555 // Update the URL in urlTextBox when the page starts to load.
557 public void onPageStarted(WebView view, String url, Bitmap favicon) {
558 // 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.
559 formattedUrlString = url;
561 // Display the loading URL is the URL text box.
562 urlTextBox.setText(url);
565 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
567 public void onPageFinished(WebView view, String url) {
568 formattedUrlString = url;
570 // Only update urlTextBox if the user is not typing in it.
571 if (!urlTextBox.hasFocus()) {
572 urlTextBox.setText(formattedUrlString);
575 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
576 sslCertificate = mainWebView.getCertificate();
579 // Handle SSL Certificate errors.
581 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
582 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
583 sslErrorHandler = handler;
585 // Display the SSL error `AlertDialog`.
586 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
587 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
591 mainWebView.setWebChromeClient(new WebChromeClient() {
592 // Update the progress bar when a page is loading.
594 public void onProgressChanged(WebView view, int progress) {
595 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
596 progressBar.setProgress(progress);
597 if (progress < 100) {
598 progressBar.setVisibility(View.VISIBLE);
600 progressBar.setVisibility(View.GONE);
602 //Stop the `SwipeToRefresh` indicator if it is running
603 swipeRefreshLayout.setRefreshing(false);
607 // Set the favorite icon when it changes.
609 public void onReceivedIcon(WebView view, Bitmap icon) {
610 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
613 // Place the favorite icon in the appBar.
614 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
615 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
618 // Enter full screen video
620 public void onShowCustomView(View view, CustomViewCallback callback) {
621 // Pause the ad if this is the free flavor.
622 if (BuildConfig.FLAVOR.contentEquals("free")) {
623 BannerAd.pauseAd(adView);
626 // Remove the translucent overlays.
627 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
629 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
630 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
632 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
633 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
634 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
636 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
638 // Set `rootCoordinatorLayout` to fill the entire screen.
639 rootCoordinatorLayout.setFitsSystemWindows(false);
641 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
642 fullScreenVideoFrameLayout.addView(view);
643 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
646 // Exit full screen video
647 public void onHideCustomView() {
648 // Hide `fullScreenVideoFrameLayout`.
649 fullScreenVideoFrameLayout.removeAllViews();
650 fullScreenVideoFrameLayout.setVisibility(View.GONE);
652 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
653 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
655 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
656 rootCoordinatorLayout.setFitsSystemWindows(true);
658 // Show the ad if this is the free flavor.
659 if (BuildConfig.FLAVOR.contentEquals("free")) {
660 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
661 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
663 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
664 adView = findViewById(R.id.adView);
669 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
670 registerForContextMenu(mainWebView);
672 // Allow the downloading of files.
673 mainWebView.setDownloadListener(new DownloadListener() {
675 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
676 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
677 AppCompatDialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
678 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
682 // Allow pinch to zoom.
683 mainWebView.getSettings().setBuiltInZoomControls(true);
685 // Hide zoom controls.
686 mainWebView.getSettings().setDisplayZoomControls(false);
688 // Initialize cookieManager.
689 cookieManager = CookieManager.getInstance();
691 // 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).
692 customHeaders.put("X-Requested-With", "");
694 // 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.
695 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
697 // Apply the settings from the shared preferences.
700 // Get the intent information that started the app.
701 final Intent intent = getIntent();
703 if (intent.getData() != null) {
704 // Get the intent data and convert it to a string.
705 final Uri intentUriData = intent.getData();
706 formattedUrlString = intentUriData.toString();
709 // If formattedUrlString is null assign the homepage to it.
710 if (formattedUrlString == null) {
711 formattedUrlString = homepage;
714 // Load the initial website.
715 mainWebView.loadUrl(formattedUrlString, customHeaders);
717 // If the favorite icon is null, load the default.
718 if (favoriteIcon == null) {
719 // We have to use `ContextCompat` until API >= 21.
720 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
721 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
722 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
725 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
726 inFullScreenBrowsingMode = false;
728 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
729 adView = findViewById(R.id.adView);
730 BannerAd.requestAd(adView);
735 protected void onNewIntent(Intent intent) {
736 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
739 if (intent.getData() != null) {
740 // Get the intent data and convert it to a string.
741 final Uri intentUriData = intent.getData();
742 formattedUrlString = intentUriData.toString();
745 // Close the navigation drawer if it is open.
746 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
747 drawerLayout.closeDrawer(GravityCompat.START);
751 mainWebView.loadUrl(formattedUrlString, customHeaders);
753 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
754 mainWebView.requestFocus();
758 public boolean onCreateOptionsMenu(Menu menu) {
759 // Inflate the menu; this adds items to the action bar if it is present.
760 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
762 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
765 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
766 updatePrivacyIcons(false);
768 // Get handles for the menu items.
769 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
770 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
771 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
772 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
774 // Only display third-Party Cookies if SDK >= 21
775 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
777 // Get the shared preference values. `this` references the current context.
778 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
780 // Set the status of the additional app bar icons. The default is `false`.
781 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
782 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
783 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
784 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
785 } else { //Do not display the additional icons.
786 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
787 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
788 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
795 public boolean onPrepareOptionsMenu(Menu menu) {
796 // Get handles for the menu items.
797 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
798 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
799 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
800 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
801 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
802 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
803 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
805 // Set the status of the menu item checkboxes.
806 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
807 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
808 toggleDomStorage.setChecked(domStorageEnabled);
809 toggleSaveFormData.setChecked(saveFormDataEnabled);
811 // Enable third-party cookies if first-party cookies are enabled.
812 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
814 // Enable DOM Storage if JavaScript is enabled.
815 toggleDomStorage.setEnabled(javaScriptEnabled);
817 // Enable Clear Cookies if there are any.
818 clearCookies.setEnabled(cookieManager.hasCookies());
820 // Enable Clear Form Data is there is any.
821 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
822 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
824 // Only show `Refresh` if `swipeToRefresh` is disabled.
825 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
827 // Initialize font size variables.
828 int fontSize = mainWebView.getSettings().getTextZoom();
829 String fontSizeTitle;
830 MenuItem selectedFontSizeMenuItem;
832 // Prepare the font size title and current size menu item.
835 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
836 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
840 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
841 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
845 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
846 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
850 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
851 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
855 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
856 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
860 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
861 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
865 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
866 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
870 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
871 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
875 // Set the font size title and select the current size menu item.
876 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
877 fontSizeMenuItem.setTitle(fontSizeTitle);
878 selectedFontSizeMenuItem.setChecked(true);
880 // Run all the other default commands.
881 super.onPrepareOptionsMenu(menu);
883 // `return true` displays the menu.
888 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
889 @SuppressLint("SetJavaScriptEnabled")
890 // removeAllCookies is deprecated, but it is required for API < 21.
891 @SuppressWarnings("deprecation")
892 public boolean onOptionsItemSelected(MenuItem menuItem) {
893 int menuItemId = menuItem.getItemId();
895 // Set the commands that relate to the menu entries.
896 switch (menuItemId) {
897 case R.id.toggleJavaScript:
898 // Switch the status of javaScriptEnabled.
899 javaScriptEnabled = !javaScriptEnabled;
901 // Apply the new JavaScript status.
902 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
904 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
905 updatePrivacyIcons(true);
907 // Display a `Snackbar`.
908 if (javaScriptEnabled) { // JavaScrip is enabled.
909 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
910 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
911 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
912 } else { // Privacy mode.
913 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
916 // Reload the WebView.
917 mainWebView.reload();
920 case R.id.toggleFirstPartyCookies:
921 // Switch the status of firstPartyCookiesEnabled.
922 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
924 // Update the menu checkbox.
925 menuItem.setChecked(firstPartyCookiesEnabled);
927 // Apply the new cookie status.
928 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
930 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
931 updatePrivacyIcons(true);
933 // Display a `Snackbar`.
934 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
935 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
936 } else if (javaScriptEnabled){ // JavaScript is still enabled.
937 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
938 } else { // Privacy mode.
939 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
942 // Reload the WebView.
943 mainWebView.reload();
946 case R.id.toggleThirdPartyCookies:
947 if (Build.VERSION.SDK_INT >= 21) {
948 // Switch the status of thirdPartyCookiesEnabled.
949 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
951 // Update the menu checkbox.
952 menuItem.setChecked(thirdPartyCookiesEnabled);
954 // Apply the new cookie status.
955 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
957 // Display a `Snackbar`.
958 if (thirdPartyCookiesEnabled) {
959 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
961 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
964 // Reload the WebView.
965 mainWebView.reload();
966 } // Else do nothing because SDK < 21.
969 case R.id.toggleDomStorage:
970 // Switch the status of domStorageEnabled.
971 domStorageEnabled = !domStorageEnabled;
973 // Update the menu checkbox.
974 menuItem.setChecked(domStorageEnabled);
976 // Apply the new DOM Storage status.
977 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
979 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
980 updatePrivacyIcons(true);
982 // Display a `Snackbar`.
983 if (domStorageEnabled) {
984 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
986 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
989 // Reload the WebView.
990 mainWebView.reload();
993 case R.id.toggleSaveFormData:
994 // Switch the status of saveFormDataEnabled.
995 saveFormDataEnabled = !saveFormDataEnabled;
997 // Update the menu checkbox.
998 menuItem.setChecked(saveFormDataEnabled);
1000 // Apply the new form data status.
1001 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1003 // Display a `Snackbar`.
1004 if (saveFormDataEnabled) {
1005 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1007 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1010 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1011 updatePrivacyIcons(true);
1013 // Reload the WebView.
1014 mainWebView.reload();
1017 case R.id.clearCookies:
1018 if (Build.VERSION.SDK_INT < 21) {
1019 cookieManager.removeAllCookie();
1021 cookieManager.removeAllCookies(null);
1023 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1026 case R.id.clearDomStorage:
1027 WebStorage webStorage = WebStorage.getInstance();
1028 webStorage.deleteAllData();
1029 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1032 case R.id.clearFormData:
1033 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1034 mainWebViewDatabase.clearFormData();
1035 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1038 case R.id.fontSizeFiftyPercent:
1039 mainWebView.getSettings().setTextZoom(50);
1042 case R.id.fontSizeSeventyFivePercent:
1043 mainWebView.getSettings().setTextZoom(75);
1046 case R.id.fontSizeOneHundredPercent:
1047 mainWebView.getSettings().setTextZoom(100);
1050 case R.id.fontSizeOneHundredTwentyFivePercent:
1051 mainWebView.getSettings().setTextZoom(125);
1054 case R.id.fontSizeOneHundredFiftyPercent:
1055 mainWebView.getSettings().setTextZoom(150);
1058 case R.id.fontSizeOneHundredSeventyFivePercent:
1059 mainWebView.getSettings().setTextZoom(175);
1062 case R.id.fontSizeTwoHundredPercent:
1063 mainWebView.getSettings().setTextZoom(200);
1066 case R.id.find_on_page:
1067 // Hide the URL app bar.
1068 supportAppBar.setVisibility(View.GONE);
1070 // Show the Find on Page `RelativeLayout`.
1071 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1073 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1074 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1075 findOnPageEditText.postDelayed(new Runnable()
1080 // Set the focus on `findOnPageEditText`.
1081 findOnPageEditText.requestFocus();
1083 // Display the keyboard.
1084 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1090 Intent shareIntent = new Intent();
1091 shareIntent.setAction(Intent.ACTION_SEND);
1092 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1093 shareIntent.setType("text/plain");
1094 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1097 case R.id.addToHomescreen:
1098 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `R.string.create_shortcut`.
1099 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
1100 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1102 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
1106 // Get a `PrintManager` instance.
1107 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1109 // Convert `mainWebView` to `printDocumentAdapter`.
1110 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1112 // Print the document. The print attributes are `null`.
1113 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1117 mainWebView.reload();
1121 // Don't consume the event.
1122 return super.onOptionsItemSelected(menuItem);
1126 // removeAllCookies is deprecated, but it is required for API < 21.
1127 @SuppressWarnings("deprecation")
1129 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1130 int menuItemId = menuItem.getItemId();
1132 switch (menuItemId) {
1134 mainWebView.loadUrl(homepage, customHeaders);
1138 if (mainWebView.canGoBack()) {
1139 mainWebView.goBack();
1144 if (mainWebView.canGoForward()) {
1145 mainWebView.goForward();
1150 // Gte the `WebBackForwardList`.
1151 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1153 // Show the `UrlHistory` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1154 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistory.loadBackForwardList(this, webBackForwardList);
1155 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1158 case R.id.bookmarks:
1159 // Launch Bookmarks.
1160 Intent bookmarksIntent = new Intent(this, Bookmarks.class);
1161 startActivity(bookmarksIntent);
1164 case R.id.downloads:
1165 // Launch the system Download Manager.
1166 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1168 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1169 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1171 startActivity(downloadManagerIntent);
1175 // Launch `Settings`.
1176 Intent settingsIntent = new Intent(this, Settings.class);
1177 startActivity(settingsIntent);
1182 Intent guideIntent = new Intent(this, Guide.class);
1183 startActivity(guideIntent);
1188 Intent aboutIntent = new Intent(this, About.class);
1189 startActivity(aboutIntent);
1192 case R.id.clearAndExit:
1193 // Clear cookies. The commands changed slightly in API 21.
1194 if (Build.VERSION.SDK_INT >= 21) {
1195 cookieManager.removeAllCookies(null);
1197 cookieManager.removeAllCookie();
1200 // Clear DOM storage.
1201 WebStorage domStorage = WebStorage.getInstance();
1202 domStorage.deleteAllData();
1205 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1206 webViewDatabase.clearFormData();
1208 // Clear cache. The argument of "true" includes disk files.
1209 mainWebView.clearCache(true);
1211 // Clear the back/forward history.
1212 mainWebView.clearHistory();
1214 // Clear any SSL certificate preferences.
1215 mainWebView.clearSslPreferences();
1217 // Clear `formattedUrlString`.
1218 formattedUrlString = null;
1220 // Clear `customHeaders`.
1221 customHeaders.clear();
1223 // Detach all views from `mainWebViewRelativeLayout`.
1224 mainWebViewRelativeLayout.removeAllViews();
1226 // Destroy the internal state of `mainWebView`.
1227 mainWebView.destroy();
1229 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1230 if (Build.VERSION.SDK_INT >= 21) {
1231 finishAndRemoveTask();
1236 // Remove the terminated program from RAM. The status code is `0`.
1244 // Close the navigation drawer.
1245 drawerLayout.closeDrawer(GravityCompat.START);
1250 public void onPostCreate(Bundle savedInstanceState) {
1251 super.onPostCreate(savedInstanceState);
1253 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1254 drawerToggle.syncState();
1258 public void onConfigurationChanged(Configuration newConfig) {
1259 super.onConfigurationChanged(newConfig);
1261 // Reload the ad for the free flavor if we are not in full screen mode.
1262 if (BuildConfig.FLAVOR.contentEquals("free") && adView.isShown() && !fullScreenVideoFrameLayout.isShown()) {
1264 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1266 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1267 adView = findViewById(R.id.adView);
1270 // `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
1271 // ActivityCompat.invalidateOptionsMenu(this);
1275 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1276 // Store the `HitTestResult`.
1277 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1280 final String imageUrl;
1281 final String linkUrl;
1283 // Get a handle for the `ClipboardManager`.
1284 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1286 switch (hitTestResult.getType()) {
1287 // `SRC_ANCHOR_TYPE` is a link.
1288 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1289 // Get the target URL.
1290 linkUrl = hitTestResult.getExtra();
1292 // Set the target URL as the title of the `ContextMenu`.
1293 menu.setHeaderTitle(linkUrl);
1295 // Add a `Load URL` entry.
1296 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1298 public boolean onMenuItemClick(MenuItem item) {
1299 mainWebView.loadUrl(linkUrl, customHeaders);
1304 // Add a `Copy URL` entry.
1305 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1307 public boolean onMenuItemClick(MenuItem item) {
1308 // Save the link URL in a `ClipData`.
1309 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1311 // Set the `ClipData` as the clipboard's primary clip.
1312 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1317 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1318 menu.add(R.string.cancel);
1321 case WebView.HitTestResult.EMAIL_TYPE:
1322 // Get the target URL.
1323 linkUrl = hitTestResult.getExtra();
1325 // Set the target URL as the title of the `ContextMenu`.
1326 menu.setHeaderTitle(linkUrl);
1328 // Add a `Write Email` entry.
1329 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1331 public boolean onMenuItemClick(MenuItem item) {
1332 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1333 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1335 // Parse the url and set it as the data for the `Intent`.
1336 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1338 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1339 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1342 startActivity(emailIntent);
1347 // Add a `Copy Email Address` entry.
1348 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1350 public boolean onMenuItemClick(MenuItem item) {
1351 // Save the email address in a `ClipData`.
1352 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1354 // Set the `ClipData` as the clipboard's primary clip.
1355 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1360 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1361 menu.add(R.string.cancel);
1364 // `IMAGE_TYPE` is an image.
1365 case WebView.HitTestResult.IMAGE_TYPE:
1366 // Get the image URL.
1367 imageUrl = hitTestResult.getExtra();
1369 // Set the image URL as the title of the `ContextMenu`.
1370 menu.setHeaderTitle(imageUrl);
1372 // Add a `View Image` entry.
1373 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1375 public boolean onMenuItemClick(MenuItem item) {
1376 mainWebView.loadUrl(imageUrl, customHeaders);
1381 // Add a `Download Image` entry.
1382 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1384 public boolean onMenuItemClick(MenuItem item) {
1385 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1386 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1387 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1392 // Add a `Copy URL` entry.
1393 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1395 public boolean onMenuItemClick(MenuItem item) {
1396 // Save the image URL in a `ClipData`.
1397 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1399 // Set the `ClipData` as the clipboard's primary clip.
1400 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1405 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1406 menu.add(R.string.cancel);
1410 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1411 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1412 // Get the image URL.
1413 imageUrl = hitTestResult.getExtra();
1415 // Set the image URL as the title of the `ContextMenu`.
1416 menu.setHeaderTitle(imageUrl);
1418 // Add a `View Image` entry.
1419 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1421 public boolean onMenuItemClick(MenuItem item) {
1422 mainWebView.loadUrl(imageUrl, customHeaders);
1427 // Add a `Download Image` entry.
1428 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1430 public boolean onMenuItemClick(MenuItem item) {
1431 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1432 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1433 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1438 // Add a `Copy URL` entry.
1439 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1441 public boolean onMenuItemClick(MenuItem item) {
1442 // Save the image URL in a `ClipData`.
1443 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1445 // Set the `ClipData` as the clipboard's primary clip.
1446 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1451 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1452 menu.add(R.string.cancel);
1458 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1459 // Get shortcutNameEditText from the alert dialog.
1460 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1462 // Create the bookmark shortcut based on formattedUrlString.
1463 Intent bookmarkShortcut = new Intent();
1464 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1465 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1467 // Place the bookmark shortcut on the home screen.
1468 Intent placeBookmarkShortcut = new Intent();
1469 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1470 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1471 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1472 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1473 sendBroadcast(placeBookmarkShortcut);
1477 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1478 // Get a handle for the system `DOWNLOAD_SERVICE`.
1479 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1481 // Parse `imageUrl`.
1482 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1484 // Get the file name from `dialogFragment`.
1485 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1486 String imageName = downloadImageNameEditText.getText().toString();
1488 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1489 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1490 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1491 } else { // Only set the title using `imageName`.
1492 downloadRequest.setTitle(imageName);
1495 // Allow `MediaScanner` to index the download if it is a media file.
1496 downloadRequest.allowScanningByMediaScanner();
1498 // Add the URL as the description for the download.
1499 downloadRequest.setDescription(imageUrl);
1501 // Show the download notification after the download is completed.
1502 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1504 // Initiate the download.
1505 downloadManager.enqueue(downloadRequest);
1509 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1510 // Get a handle for the system `DOWNLOAD_SERVICE`.
1511 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1513 // Parse `downloadUrl`.
1514 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1516 // Get the file name from `dialogFragment`.
1517 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1518 String fileName = downloadFileNameEditText.getText().toString();
1520 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1521 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `fileName`.
1522 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1523 } else { // Only set the title using `fileName`.
1524 downloadRequest.setTitle(fileName);
1527 // Allow `MediaScanner` to index the download if it is a media file.
1528 downloadRequest.allowScanningByMediaScanner();
1530 // Add the URL as the description for the download.
1531 downloadRequest.setDescription(downloadUrl);
1533 // Show the download notification after the download is completed.
1534 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1536 // Initiate the download.
1537 downloadManager.enqueue(downloadRequest);
1540 public void viewSslCertificate(View view) {
1541 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1542 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1543 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1547 public void onSslErrorCancel() {
1548 sslErrorHandler.cancel();
1552 public void onSslErrorProceed() {
1553 sslErrorHandler.proceed();
1557 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1558 // Load the history entry.
1559 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1563 public void onClearHistory() {
1564 // Clear the history.
1565 mainWebView.clearHistory();
1568 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1570 public void onBackPressed() {
1571 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1572 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1573 drawerLayout.closeDrawer(GravityCompat.START);
1575 // Load the previous URL if available.
1576 if (mainWebView.canGoBack()) {
1577 mainWebView.goBack();
1579 // Pass `onBackPressed()` to the system.
1580 super.onBackPressed();
1586 public void onPause() {
1587 // Pause `mainWebView`.
1588 mainWebView.onPause();
1590 // Stop all JavaScript.
1591 mainWebView.pauseTimers();
1593 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1594 if (BuildConfig.FLAVOR.contentEquals("free")) {
1595 BannerAd.pauseAd(adView);
1602 public void onResume() {
1605 // Resume JavaScript (if enabled).
1606 mainWebView.resumeTimers();
1608 // Resume `mainWebView`.
1609 mainWebView.onResume();
1611 // Resume the adView for the free flavor.
1612 if (BuildConfig.FLAVOR.contentEquals("free")) {
1613 BannerAd.resumeAd(adView);
1618 public void onRestart() {
1621 // Apply the settings from shared preferences, which might have been changed in `Settings`.
1624 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1625 updatePrivacyIcons(true);
1629 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1630 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1631 String unformattedUrlString = urlTextBox.getText().toString().trim();
1633 URL unformattedUrl = null;
1634 Uri.Builder formattedUri = new Uri.Builder();
1636 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1637 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1638 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1639 if (!unformattedUrlString.startsWith("http")) {
1640 unformattedUrlString = "http://" + unformattedUrlString;
1643 // 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.
1645 unformattedUrl = new URL(unformattedUrlString);
1646 } catch (MalformedURLException e) {
1647 e.printStackTrace();
1650 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1651 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1652 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1653 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1654 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1655 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1657 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1658 formattedUrlString = formattedUri.build().toString();
1660 // Sanitize the search input and convert it to a DuckDuckGo search.
1661 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1663 // Use the correct search URL.
1664 if (javaScriptEnabled) { // JavaScript is enabled.
1665 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1666 } else { // JavaScript is disabled.
1667 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1671 mainWebView.loadUrl(formattedUrlString, customHeaders);
1673 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1674 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1677 public void findPreviousOnPage(View view) {
1678 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
1679 mainWebView.findNext(false);
1682 public void findNextOnPage(View view) {
1683 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
1684 mainWebView.findNext(true);
1687 public void closeFindOnPage(View view) {
1688 // Delete the contents of `find_on_page_edittext`.
1689 findOnPageEditText.setText(null);
1691 // Clear the highlighted phrases.
1692 mainWebView.clearMatches();
1694 // Hide the Find on Page `RelativeLayout`.
1695 findOnPageLinearLayout.setVisibility(View.GONE);
1697 // Show the URL app bar.
1698 supportAppBar.setVisibility(View.VISIBLE);
1700 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1701 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1704 private void applySettings() {
1705 // Get the shared preference values. `this` references the current context.
1706 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1708 // Store the values from `sharedPreferences` in variables.
1709 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
1710 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1711 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1712 String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1713 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1714 String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1715 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1716 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1717 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1718 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
1719 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
1720 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1721 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
1722 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
1723 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
1725 // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1726 if (javaScriptEnabled == null) { // If `javaScriptEnabled` is null the program is just starting.
1727 // Get the values from `sharedPreferences`.
1728 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1729 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1730 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1731 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1732 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1734 // Apply the default settings.
1735 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1736 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1737 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1738 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1739 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1741 // Set third-party cookies status if API >= 21.
1742 if (Build.VERSION.SDK_INT >= 21) {
1743 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1747 // Apply the other settings from `sharedPreferences`.
1748 homepage = homepageString;
1749 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1751 // Set the user agent initial status.
1752 switch (userAgentString) {
1753 case "Default user agent":
1754 // Set the user agent to `""`, which uses the default value.
1755 mainWebView.getSettings().setUserAgentString("");
1758 case "Custom user agent":
1759 // Set the custom user agent.
1760 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1764 // Use the selected user agent.
1765 mainWebView.getSettings().setUserAgentString(userAgentString);
1769 // Set JavaScript disabled search.
1770 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1771 javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1772 } else { // Use the string from the pre-built list.
1773 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1776 // Set JavaScript enabled search.
1777 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1778 javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1779 } else { // Use the string from the pre-built list.
1780 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1783 // Set Do Not Track status.
1784 if (doNotTrackEnabled) {
1785 customHeaders.put("DNT", "1");
1787 customHeaders.remove("DNT");
1790 // Set Orbot proxy status.
1791 if (proxyThroughOrbot) {
1792 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
1793 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1794 } else { // Reset the proxy to default. The host is `""` and the port is `"0"`.
1795 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1798 // If we are in full screen mode update the `SYSTEM_UI` flags.
1799 if (inFullScreenBrowsingMode) {
1800 if (hideSystemBarsOnFullscreen) { // Hide everything.
1801 // Remove the translucent navigation setting if it is currently flagged.
1802 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1804 // Remove the translucent status bar overlay.
1805 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1807 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1808 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1810 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1811 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1812 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1814 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1815 } else { // Hide everything except the status and navigation bars.
1816 // Add the translucent status flag if it is unset.
1817 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1819 if (translucentNavigationBarOnFullscreen) {
1820 // Set the navigation bar to be translucent.
1821 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1823 // Set the navigation bar to be black.
1824 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1830 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
1831 // Get handles for the icons.
1832 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1833 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1834 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1835 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1837 // Update `privacyIcon`.
1838 if (javaScriptEnabled) { // JavaScript is enabled.
1839 privacyIcon.setIcon(R.drawable.javascript_enabled);
1840 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1841 privacyIcon.setIcon(R.drawable.warning);
1842 } else { // All the dangerous features are disabled.
1843 privacyIcon.setIcon(R.drawable.privacy_mode);
1846 // Update `firstPartyCookiesIcon`.
1847 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1848 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1849 } else { // First-party cookies are disabled.
1850 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1853 // Update `domStorageIcon`.
1854 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
1855 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1856 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
1857 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1858 } else { // JavaScript is disabled, so DOM storage is ghosted.
1859 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1862 // Update `formDataIcon`.
1863 if (saveFormDataEnabled) { // Form data is enabled.
1864 formDataIcon.setIcon(R.drawable.form_data_enabled);
1865 } else { // Form data is disabled.
1866 formDataIcon.setIcon(R.drawable.form_data_disabled);
1869 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
1870 if (runInvalidateOptionsMenu) {
1871 ActivityCompat.invalidateOptionsMenu(this);