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.Log;
61 import android.util.Patterns;
62 import android.view.ContextMenu;
63 import android.view.GestureDetector;
64 import android.view.KeyEvent;
65 import android.view.Menu;
66 import android.view.MenuItem;
67 import android.view.MotionEvent;
68 import android.view.View;
69 import android.view.WindowManager;
70 import android.view.inputmethod.InputMethodManager;
71 import android.webkit.CookieManager;
72 import android.webkit.DownloadListener;
73 import android.webkit.SslErrorHandler;
74 import android.webkit.WebBackForwardList;
75 import android.webkit.WebChromeClient;
76 import android.webkit.WebResourceResponse;
77 import android.webkit.WebStorage;
78 import android.webkit.WebView;
79 import android.webkit.WebViewClient;
80 import android.webkit.WebViewDatabase;
81 import android.widget.EditText;
82 import android.widget.FrameLayout;
83 import android.widget.ImageView;
84 import android.widget.LinearLayout;
85 import android.widget.ProgressBar;
86 import android.widget.RelativeLayout;
87 import android.widget.TextView;
89 import com.stoutner.privacybrowser.BannerAd;
90 import com.stoutner.privacybrowser.BuildConfig;
91 import com.stoutner.privacybrowser.R;
92 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
93 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcut;
94 import com.stoutner.privacybrowser.dialogs.DownloadFile;
95 import com.stoutner.privacybrowser.dialogs.DownloadImage;
96 import com.stoutner.privacybrowser.dialogs.SslCertificateError;
97 import com.stoutner.privacybrowser.dialogs.UrlHistory;
98 import com.stoutner.privacybrowser.dialogs.ViewSslCertificate;
100 import java.io.BufferedReader;
101 import java.io.ByteArrayInputStream;
102 import java.io.IOException;
103 import java.io.InputStreamReader;
104 import java.io.UnsupportedEncodingException;
105 import java.net.MalformedURLException;
107 import java.net.URLEncoder;
108 import java.util.HashMap;
109 import java.util.HashSet;
110 import java.util.Map;
111 import java.util.Set;
113 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
114 public class MainWebView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
115 SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener, DownloadImage.DownloadImageListener, UrlHistory.UrlHistoryListener {
117 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
118 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applySettings()`.
119 public static ActionBar appBar;
121 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `Bookmarks`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
122 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
123 public static Bitmap favoriteIcon;
125 // `formattedUrlString` is public static so it can be accessed from `Bookmarks`.
126 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
127 public static String formattedUrlString;
129 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`. It is also used in `onCreate()`.
130 public static SslCertificate sslCertificate;
133 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
134 private DrawerLayout drawerLayout;
136 // `rootCoordinatorLayout` is used in `onCreate()` and `applySettings()`.
137 private CoordinatorLayout rootCoordinatorLayout;
139 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
140 private WebView mainWebView;
142 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
143 private FrameLayout fullScreenVideoFrameLayout;
145 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
146 private SwipeRefreshLayout swipeRefreshLayout;
148 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
149 private CookieManager cookieManager;
151 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrlFromTextBox()`.
152 private final Map<String, String> customHeaders = new HashMap<>();
154 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
155 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
156 private Boolean javaScriptEnabled;
158 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applySettings()`.
159 private boolean firstPartyCookiesEnabled;
161 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
162 private boolean thirdPartyCookiesEnabled;
164 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
165 private boolean domStorageEnabled;
167 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
168 private boolean saveFormDataEnabled;
170 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
171 private boolean swipeToRefreshEnabled;
173 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
174 private String homepage;
176 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
177 private String javaScriptDisabledSearchURL;
179 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
180 private String javaScriptEnabledSearchURL;
182 // `adBlockerEnabled` is used in `onCreate()` and `applySettings()`.
183 private boolean adBlockerEnabled;
185 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applySettings()`.
186 private boolean fullScreenBrowsingModeEnabled;
188 // `inFullScreenBrowsingMode` is used in `onCreate()` and `applySettings()`.
189 private boolean inFullScreenBrowsingMode;
191 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
192 private boolean hideSystemBarsOnFullscreen;
194 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
195 private boolean translucentNavigationBarOnFullscreen;
197 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
198 private LinearLayout findOnPageLinearLayout;
200 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
201 private EditText findOnPageEditText;
203 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
204 private Menu mainMenu;
206 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
207 private ActionBarDrawerToggle drawerToggle;
209 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
210 private Toolbar supportAppBar;
212 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
213 private EditText urlTextBox;
215 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
218 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
219 private SslErrorHandler sslErrorHandler;
221 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
222 private InputMethodManager inputMethodManager;
224 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
225 private RelativeLayout mainWebViewRelativeLayout;
228 // 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.
229 @SuppressLint("SetJavaScriptEnabled")
230 protected void onCreate(Bundle savedInstanceState) {
231 super.onCreate(savedInstanceState);
232 setContentView(R.layout.drawerlayout);
234 // Get a handle for `inputMethodManager`.
235 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
237 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
238 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
239 setSupportActionBar(supportAppBar);
240 appBar = getSupportActionBar();
242 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
243 assert appBar != null;
245 // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
246 appBar.setCustomView(R.layout.url_app_bar);
247 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
249 // Set the "go" button on the keyboard to load the URL in urlTextBox.
250 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
251 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
253 public boolean onKey(View v, int keyCode, KeyEvent event) {
254 // If the event is a key-down event on the `enter` button, load the URL.
255 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
256 // Load the URL into the mainWebView and consume the event.
258 loadUrlFromTextBox();
259 } catch (UnsupportedEncodingException e) {
262 // If the enter key was pressed, consume the event.
265 // If any other key was pressed, do not consume the event.
271 // Get handles for views that need to be accessed.
272 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
273 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
274 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
275 mainWebView = (WebView) findViewById(R.id.mainWebView);
276 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
277 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
278 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
280 // Create a double-tap listener to toggle full-screen mode.
281 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
282 // Override `onDoubleTap()`. All other events are handled using the default settings.
284 public boolean onDoubleTap(MotionEvent event) {
285 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
286 // Toggle `inFullScreenBrowsingMode`.
287 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
289 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
290 // Hide the `appBar`.
293 // Hide the `BannerAd` in the free flavor.
294 if (BuildConfig.FLAVOR.contentEquals("free")) {
295 BannerAd.hideAd(adView);
298 // Modify the system bars.
299 if (hideSystemBarsOnFullscreen) { // Hide everything.
300 // Remove the translucent overlays.
301 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
303 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
304 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
306 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
307 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
308 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
310 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
312 // Set `rootCoordinatorLayout` to fill the whole screen.
313 rootCoordinatorLayout.setFitsSystemWindows(false);
314 } else { // Hide everything except the status and navigation bars.
315 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
316 rootCoordinatorLayout.setFitsSystemWindows(false);
318 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.
319 // Set the navigation bar to be translucent.
320 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
323 } else { // Switch to normal viewing mode.
324 // Show the `appBar`.
327 // Show the `BannerAd` in the free flavor.
328 if (BuildConfig.FLAVOR.contentEquals("free")) {
329 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
330 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
332 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
333 adView = findViewById(R.id.adView);
336 // Remove the translucent navigation bar flag if it is set.
337 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
339 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
340 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
342 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
343 rootCoordinatorLayout.setSystemUiVisibility(0);
345 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
346 rootCoordinatorLayout.setFitsSystemWindows(true);
349 // Consume the double-tap.
351 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
357 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
358 mainWebView.setOnTouchListener(new View.OnTouchListener() {
360 public boolean onTouch(View v, MotionEvent event) {
361 // Send the `event` to `gestureDetector`.
362 return gestureDetector.onTouchEvent(event);
366 // Update `findOnPageCountTextView`.
367 mainWebView.setFindListener(new WebView.FindListener() {
368 // Get a handle for `findOnPageCountTextView`.
369 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
372 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
373 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
374 // Set `findOnPageCountTextView` to `0/0`.
375 findOnPageCountTextView.setText(R.string.zero_of_zero);
376 } else if (isDoneCounting) { // There are matches.
377 // `activeMatchOrdinal` is zero-based.
378 int activeMatch = activeMatchOrdinal + 1;
380 // Set `findOnPageCountTextView`.
381 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
386 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
387 findOnPageEditText.addTextChangedListener(new TextWatcher() {
389 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
394 public void onTextChanged(CharSequence s, int start, int before, int count) {
399 public void afterTextChanged(Editable s) {
400 // Search for the text in `mainWebView`.
401 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
405 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
406 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
408 public boolean onKey(View v, int keyCode, KeyEvent event) {
409 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
410 // Hide the soft keyboard. `0` indicates no additional flags.
411 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
413 // Consume the event.
415 } else { // A different key was pressed.
416 // Do not consume the event.
422 // Implement swipe to refresh
423 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
424 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
425 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
427 public void onRefresh() {
428 mainWebView.reload();
432 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
433 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
435 // Listen for touches on the navigation menu.
436 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
437 navigationView.setNavigationItemSelectedListener(this);
439 // 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.
440 final Menu navigationMenu = navigationView.getMenu();
441 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
442 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
443 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
445 // The `DrawerListener` allows us to update the Navigation Menu.
446 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
448 public void onDrawerSlide(View drawerView, float slideOffset) {
452 public void onDrawerOpened(View drawerView) {
456 public void onDrawerClosed(View drawerView) {
460 public void onDrawerStateChanged(int newState) {
461 // Update the `Back`, `Forward`, and `History` menu items every time the drawer opens.
462 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
463 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
464 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
466 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
467 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
471 // drawerToggle creates the hamburger icon at the start of the AppBar.
472 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
474 // Initialize `adServerSet`.
475 final Set<String> adServersSet = new HashSet<>();
477 // Load the list of ad servers into memory.
479 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
480 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
482 // Create a string for storing each ad server.
485 // Populate `adServersSet`.
486 while ((adServer = bufferedReader.readLine()) != null) {
487 adServersSet.add(adServer);
490 // Close `bufferedReader`.
491 bufferedReader.close();
492 } catch (IOException ioException) {
493 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
496 mainWebView.setWebViewClient(new WebViewClient() {
497 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
498 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
499 @SuppressWarnings("deprecation")
501 public boolean shouldOverrideUrlLoading(WebView view, String url) {
502 // Use an external email program if the link begins with `mailto:`.
503 if (url.startsWith("mailto:")) {
504 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
505 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
507 // Parse the url and set it as the data for the `Intent`.
508 emailIntent.setData(Uri.parse(url));
510 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
511 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
514 startActivity(emailIntent);
516 } else { // Load the URL in Privacy Browser.
517 mainWebView.loadUrl(url, customHeaders);
522 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
523 @SuppressWarnings("deprecation")
525 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
526 if (adBlockerEnabled) { // Block ads.
527 // Extract the host from `url`.
528 Uri requestUri = Uri.parse(url);
529 String requestHost = requestUri.getHost();
531 // Create a variable to track if this is an ad server.
532 boolean requestHostIsAdServer = false;
534 // Check all the subdomains of `requestHost` if it is not `null`.
535 if (requestHost != null) {
536 while (requestHost.contains(".")) {
537 if (adServersSet.contains(requestHost)) {
538 requestHostIsAdServer = true;
541 // Strip out the lowest subdomain of `requestHost`.
542 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
546 if (requestHostIsAdServer) { // It is an ad server.
547 // Return an empty `WebResourceResponse`.
548 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
549 } else { // It is not an ad server.
550 // `return null` loads the requested resource.
553 } else { // Ad blocking is disabled.
554 // `return null` loads the requested resource.
559 // Update the URL in urlTextBox when the page starts to load.
561 public void onPageStarted(WebView view, String url, Bitmap favicon) {
562 // 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.
563 formattedUrlString = url;
565 // Display the loading URL is the URL text box.
566 urlTextBox.setText(url);
569 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
571 public void onPageFinished(WebView view, String url) {
572 formattedUrlString = url;
574 // Only update urlTextBox if the user is not typing in it.
575 if (!urlTextBox.hasFocus()) {
576 urlTextBox.setText(formattedUrlString);
579 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
580 sslCertificate = mainWebView.getCertificate();
583 // Handle SSL Certificate errors.
585 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
586 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
587 sslErrorHandler = handler;
589 // Display the SSL error `AlertDialog`.
590 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
591 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
595 mainWebView.setWebChromeClient(new WebChromeClient() {
596 // Update the progress bar when a page is loading.
598 public void onProgressChanged(WebView view, int progress) {
599 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
600 progressBar.setProgress(progress);
601 if (progress < 100) {
602 progressBar.setVisibility(View.VISIBLE);
604 progressBar.setVisibility(View.GONE);
606 //Stop the `SwipeToRefresh` indicator if it is running
607 swipeRefreshLayout.setRefreshing(false);
611 // Set the favorite icon when it changes.
613 public void onReceivedIcon(WebView view, Bitmap icon) {
614 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
617 // Place the favorite icon in the appBar.
618 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
619 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
622 // Enter full screen video
624 public void onShowCustomView(View view, CustomViewCallback callback) {
625 // Pause the ad if this is the free flavor.
626 if (BuildConfig.FLAVOR.contentEquals("free")) {
627 BannerAd.pauseAd(adView);
630 // Remove the translucent overlays.
631 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
633 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
634 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
636 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
637 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
638 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
640 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
642 // Set `rootCoordinatorLayout` to fill the entire screen.
643 rootCoordinatorLayout.setFitsSystemWindows(false);
645 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
646 fullScreenVideoFrameLayout.addView(view);
647 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
650 // Exit full screen video
651 public void onHideCustomView() {
652 // Hide `fullScreenVideoFrameLayout`.
653 fullScreenVideoFrameLayout.removeAllViews();
654 fullScreenVideoFrameLayout.setVisibility(View.GONE);
656 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
657 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
659 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
660 rootCoordinatorLayout.setFitsSystemWindows(true);
662 // Show the ad if this is the free flavor.
663 if (BuildConfig.FLAVOR.contentEquals("free")) {
664 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
665 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
667 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
668 adView = findViewById(R.id.adView);
673 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
674 registerForContextMenu(mainWebView);
676 // Allow the downloading of files.
677 mainWebView.setDownloadListener(new DownloadListener() {
679 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
680 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
681 AppCompatDialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
682 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
686 // Allow pinch to zoom.
687 mainWebView.getSettings().setBuiltInZoomControls(true);
689 // Hide zoom controls.
690 mainWebView.getSettings().setDisplayZoomControls(false);
692 // Initialize cookieManager.
693 cookieManager = CookieManager.getInstance();
695 // 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).
696 customHeaders.put("X-Requested-With", "");
698 // 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.
699 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
701 // Apply the settings from the shared preferences.
704 // Get the intent information that started the app.
705 final Intent intent = getIntent();
707 if (intent.getData() != null) {
708 // Get the intent data and convert it to a string.
709 final Uri intentUriData = intent.getData();
710 formattedUrlString = intentUriData.toString();
713 // If formattedUrlString is null assign the homepage to it.
714 if (formattedUrlString == null) {
715 formattedUrlString = homepage;
718 // Load the initial website.
719 mainWebView.loadUrl(formattedUrlString, customHeaders);
721 // If the favorite icon is null, load the default.
722 if (favoriteIcon == null) {
723 // We have to use `ContextCompat` until API >= 21.
724 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
725 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
726 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
729 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
730 inFullScreenBrowsingMode = false;
732 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
733 adView = findViewById(R.id.adView);
734 BannerAd.requestAd(adView);
739 protected void onNewIntent(Intent intent) {
740 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
743 if (intent.getData() != null) {
744 // Get the intent data and convert it to a string.
745 final Uri intentUriData = intent.getData();
746 formattedUrlString = intentUriData.toString();
749 // Close the navigation drawer if it is open.
750 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
751 drawerLayout.closeDrawer(GravityCompat.START);
755 mainWebView.loadUrl(formattedUrlString, customHeaders);
757 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
758 mainWebView.requestFocus();
762 public boolean onCreateOptionsMenu(Menu menu) {
763 // Inflate the menu; this adds items to the action bar if it is present.
764 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
766 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
769 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
770 updatePrivacyIcons(false);
772 // Get handles for the menu items.
773 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
774 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
775 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
776 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
778 // Only display third-Party Cookies if SDK >= 21
779 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
781 // Get the shared preference values. `this` references the current context.
782 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
784 // Set the status of the additional app bar icons. The default is `false`.
785 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
786 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
787 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
788 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
789 } else { //Do not display the additional icons.
790 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
791 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
792 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
799 public boolean onPrepareOptionsMenu(Menu menu) {
800 // Get handles for the menu items.
801 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
802 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
803 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
804 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
805 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
806 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
807 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
809 // Set the status of the menu item checkboxes.
810 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
811 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
812 toggleDomStorage.setChecked(domStorageEnabled);
813 toggleSaveFormData.setChecked(saveFormDataEnabled);
815 // Enable third-party cookies if first-party cookies are enabled.
816 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
818 // Enable DOM Storage if JavaScript is enabled.
819 toggleDomStorage.setEnabled(javaScriptEnabled);
821 // Enable Clear Cookies if there are any.
822 clearCookies.setEnabled(cookieManager.hasCookies());
824 // Enable Clear Form Data is there is any.
825 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
826 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
828 // Only show `Refresh` if `swipeToRefresh` is disabled.
829 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
831 // Initialize font size variables.
832 int fontSize = mainWebView.getSettings().getTextZoom();
833 String fontSizeTitle;
834 MenuItem selectedFontSizeMenuItem;
836 // Prepare the font size title and current size menu item.
839 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
840 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
844 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
845 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
849 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
850 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
854 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
855 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
859 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
860 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
864 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
865 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
869 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
870 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
874 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
875 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
879 // Set the font size title and select the current size menu item.
880 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
881 fontSizeMenuItem.setTitle(fontSizeTitle);
882 selectedFontSizeMenuItem.setChecked(true);
884 // Run all the other default commands.
885 super.onPrepareOptionsMenu(menu);
887 // `return true` displays the menu.
892 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
893 @SuppressLint("SetJavaScriptEnabled")
894 // removeAllCookies is deprecated, but it is required for API < 21.
895 @SuppressWarnings("deprecation")
896 public boolean onOptionsItemSelected(MenuItem menuItem) {
897 int menuItemId = menuItem.getItemId();
899 // Set the commands that relate to the menu entries.
900 switch (menuItemId) {
901 case R.id.toggleJavaScript:
902 // Switch the status of javaScriptEnabled.
903 javaScriptEnabled = !javaScriptEnabled;
905 // Apply the new JavaScript status.
906 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
908 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
909 updatePrivacyIcons(true);
911 // Display a `Snackbar`.
912 if (javaScriptEnabled) { // JavaScrip is enabled.
913 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
914 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
915 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
916 } else { // Privacy mode.
917 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
920 // Reload the WebView.
921 mainWebView.reload();
924 case R.id.toggleFirstPartyCookies:
925 // Switch the status of firstPartyCookiesEnabled.
926 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
928 // Update the menu checkbox.
929 menuItem.setChecked(firstPartyCookiesEnabled);
931 // Apply the new cookie status.
932 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
934 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
935 updatePrivacyIcons(true);
937 // Display a `Snackbar`.
938 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
939 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
940 } else if (javaScriptEnabled){ // JavaScript is still enabled.
941 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
942 } else { // Privacy mode.
943 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
946 // Reload the WebView.
947 mainWebView.reload();
950 case R.id.toggleThirdPartyCookies:
951 if (Build.VERSION.SDK_INT >= 21) {
952 // Switch the status of thirdPartyCookiesEnabled.
953 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
955 // Update the menu checkbox.
956 menuItem.setChecked(thirdPartyCookiesEnabled);
958 // Apply the new cookie status.
959 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
961 // Display a `Snackbar`.
962 if (thirdPartyCookiesEnabled) {
963 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
965 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
968 // Reload the WebView.
969 mainWebView.reload();
970 } // Else do nothing because SDK < 21.
973 case R.id.toggleDomStorage:
974 // Switch the status of domStorageEnabled.
975 domStorageEnabled = !domStorageEnabled;
977 // Update the menu checkbox.
978 menuItem.setChecked(domStorageEnabled);
980 // Apply the new DOM Storage status.
981 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
983 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
984 updatePrivacyIcons(true);
986 // Display a `Snackbar`.
987 if (domStorageEnabled) {
988 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
990 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
993 // Reload the WebView.
994 mainWebView.reload();
997 case R.id.toggleSaveFormData:
998 // Switch the status of saveFormDataEnabled.
999 saveFormDataEnabled = !saveFormDataEnabled;
1001 // Update the menu checkbox.
1002 menuItem.setChecked(saveFormDataEnabled);
1004 // Apply the new form data status.
1005 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1007 // Display a `Snackbar`.
1008 if (saveFormDataEnabled) {
1009 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1011 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1014 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1015 updatePrivacyIcons(true);
1017 // Reload the WebView.
1018 mainWebView.reload();
1021 case R.id.clearCookies:
1022 if (Build.VERSION.SDK_INT < 21) {
1023 cookieManager.removeAllCookie();
1025 cookieManager.removeAllCookies(null);
1027 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1030 case R.id.clearDomStorage:
1031 WebStorage webStorage = WebStorage.getInstance();
1032 webStorage.deleteAllData();
1033 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1036 case R.id.clearFormData:
1037 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1038 mainWebViewDatabase.clearFormData();
1039 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1042 case R.id.fontSizeFiftyPercent:
1043 mainWebView.getSettings().setTextZoom(50);
1046 case R.id.fontSizeSeventyFivePercent:
1047 mainWebView.getSettings().setTextZoom(75);
1050 case R.id.fontSizeOneHundredPercent:
1051 mainWebView.getSettings().setTextZoom(100);
1054 case R.id.fontSizeOneHundredTwentyFivePercent:
1055 mainWebView.getSettings().setTextZoom(125);
1058 case R.id.fontSizeOneHundredFiftyPercent:
1059 mainWebView.getSettings().setTextZoom(150);
1062 case R.id.fontSizeOneHundredSeventyFivePercent:
1063 mainWebView.getSettings().setTextZoom(175);
1066 case R.id.fontSizeTwoHundredPercent:
1067 mainWebView.getSettings().setTextZoom(200);
1070 case R.id.find_on_page:
1071 // Hide the URL app bar.
1072 supportAppBar.setVisibility(View.GONE);
1074 // Show the Find on Page `RelativeLayout`.
1075 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1077 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1078 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1079 findOnPageEditText.postDelayed(new Runnable()
1084 // Set the focus on `findOnPageEditText`.
1085 findOnPageEditText.requestFocus();
1087 // Display the keyboard.
1088 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1094 Intent shareIntent = new Intent();
1095 shareIntent.setAction(Intent.ACTION_SEND);
1096 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1097 shareIntent.setType("text/plain");
1098 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1101 case R.id.addToHomescreen:
1102 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `R.string.create_shortcut`.
1103 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
1104 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1106 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
1110 // Get a `PrintManager` instance.
1111 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1113 // Convert `mainWebView` to `printDocumentAdapter`.
1114 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1116 // Print the document. The print attributes are `null`.
1117 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1121 mainWebView.reload();
1125 // Don't consume the event.
1126 return super.onOptionsItemSelected(menuItem);
1130 // removeAllCookies is deprecated, but it is required for API < 21.
1131 @SuppressWarnings("deprecation")
1133 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1134 int menuItemId = menuItem.getItemId();
1136 switch (menuItemId) {
1138 mainWebView.loadUrl(homepage, customHeaders);
1142 if (mainWebView.canGoBack()) {
1143 mainWebView.goBack();
1148 if (mainWebView.canGoForward()) {
1149 mainWebView.goForward();
1154 // Gte the `WebBackForwardList`.
1155 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1157 // Show the `UrlHistory` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1158 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistory.loadBackForwardList(this, webBackForwardList);
1159 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1162 case R.id.bookmarks:
1163 // Launch Bookmarks.
1164 Intent bookmarksIntent = new Intent(this, Bookmarks.class);
1165 startActivity(bookmarksIntent);
1168 case R.id.downloads:
1169 // Launch the system Download Manager.
1170 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1172 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1173 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1175 startActivity(downloadManagerIntent);
1179 // Launch `Settings`.
1180 Intent settingsIntent = new Intent(this, Settings.class);
1181 startActivity(settingsIntent);
1186 Intent guideIntent = new Intent(this, Guide.class);
1187 startActivity(guideIntent);
1192 Intent aboutIntent = new Intent(this, About.class);
1193 startActivity(aboutIntent);
1196 case R.id.clearAndExit:
1197 // Clear cookies. The commands changed slightly in API 21.
1198 if (Build.VERSION.SDK_INT >= 21) {
1199 cookieManager.removeAllCookies(null);
1201 cookieManager.removeAllCookie();
1204 // Clear DOM storage.
1205 WebStorage domStorage = WebStorage.getInstance();
1206 domStorage.deleteAllData();
1209 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1210 webViewDatabase.clearFormData();
1212 // Clear cache. The argument of "true" includes disk files.
1213 mainWebView.clearCache(true);
1215 // Clear the back/forward history.
1216 mainWebView.clearHistory();
1218 // Clear any SSL certificate preferences.
1219 mainWebView.clearSslPreferences();
1221 // Clear `formattedUrlString`.
1222 formattedUrlString = null;
1224 // Clear `customHeaders`.
1225 customHeaders.clear();
1227 // Detach all views from `mainWebViewRelativeLayout`.
1228 mainWebViewRelativeLayout.removeAllViews();
1230 // Destroy the internal state of `mainWebView`.
1231 mainWebView.destroy();
1233 // Manually delete the `app_webview` folder, which contains an additional `WebView` cache. See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1234 Runtime runtime = Runtime.getRuntime();
1235 String dataDirString = getApplicationInfo().dataDir; // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1237 runtime.exec("rm -rf " + dataDirString + "/app_webview");
1238 } catch (IOException e) {
1239 // Do nothing if the files do not exist.
1242 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1243 if (Build.VERSION.SDK_INT >= 21) {
1244 finishAndRemoveTask();
1249 // Remove the terminated program from RAM. The status code is `0`.
1257 // Close the navigation drawer.
1258 drawerLayout.closeDrawer(GravityCompat.START);
1263 public void onPostCreate(Bundle savedInstanceState) {
1264 super.onPostCreate(savedInstanceState);
1266 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1267 drawerToggle.syncState();
1271 public void onConfigurationChanged(Configuration newConfig) {
1272 super.onConfigurationChanged(newConfig);
1274 // Reload the ad for the free flavor if we are not in full screen mode.
1275 if (BuildConfig.FLAVOR.contentEquals("free") && adView.isShown() && !fullScreenVideoFrameLayout.isShown()) {
1277 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1279 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1280 adView = findViewById(R.id.adView);
1283 // `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
1284 // ActivityCompat.invalidateOptionsMenu(this);
1288 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1289 // Store the `HitTestResult`.
1290 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1293 final String imageUrl;
1294 final String linkUrl;
1296 // Get a handle for the `ClipboardManager`.
1297 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1299 switch (hitTestResult.getType()) {
1300 // `SRC_ANCHOR_TYPE` is a link.
1301 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1302 // Get the target URL.
1303 linkUrl = hitTestResult.getExtra();
1305 // Set the target URL as the title of the `ContextMenu`.
1306 menu.setHeaderTitle(linkUrl);
1308 // Add a `Load URL` entry.
1309 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1311 public boolean onMenuItemClick(MenuItem item) {
1312 mainWebView.loadUrl(linkUrl, customHeaders);
1317 // Add a `Copy URL` entry.
1318 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1320 public boolean onMenuItemClick(MenuItem item) {
1321 // Save the link URL in a `ClipData`.
1322 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1324 // Set the `ClipData` as the clipboard's primary clip.
1325 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1330 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1331 menu.add(R.string.cancel);
1334 case WebView.HitTestResult.EMAIL_TYPE:
1335 // Get the target URL.
1336 linkUrl = hitTestResult.getExtra();
1338 // Set the target URL as the title of the `ContextMenu`.
1339 menu.setHeaderTitle(linkUrl);
1341 // Add a `Write Email` entry.
1342 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1344 public boolean onMenuItemClick(MenuItem item) {
1345 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1346 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1348 // Parse the url and set it as the data for the `Intent`.
1349 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1351 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1352 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1355 startActivity(emailIntent);
1360 // Add a `Copy Email Address` entry.
1361 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1363 public boolean onMenuItemClick(MenuItem item) {
1364 // Save the email address in a `ClipData`.
1365 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1367 // Set the `ClipData` as the clipboard's primary clip.
1368 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1373 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1374 menu.add(R.string.cancel);
1377 // `IMAGE_TYPE` is an image.
1378 case WebView.HitTestResult.IMAGE_TYPE:
1379 // Get the image URL.
1380 imageUrl = hitTestResult.getExtra();
1382 // Set the image URL as the title of the `ContextMenu`.
1383 menu.setHeaderTitle(imageUrl);
1385 // Add a `View Image` entry.
1386 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1388 public boolean onMenuItemClick(MenuItem item) {
1389 mainWebView.loadUrl(imageUrl, customHeaders);
1394 // Add a `Download Image` entry.
1395 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1397 public boolean onMenuItemClick(MenuItem item) {
1398 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1399 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1400 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1405 // Add a `Copy URL` entry.
1406 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1408 public boolean onMenuItemClick(MenuItem item) {
1409 // Save the image URL in a `ClipData`.
1410 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1412 // Set the `ClipData` as the clipboard's primary clip.
1413 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1418 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1419 menu.add(R.string.cancel);
1423 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1424 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1425 // Get the image URL.
1426 imageUrl = hitTestResult.getExtra();
1428 // Set the image URL as the title of the `ContextMenu`.
1429 menu.setHeaderTitle(imageUrl);
1431 // Add a `View Image` entry.
1432 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1434 public boolean onMenuItemClick(MenuItem item) {
1435 mainWebView.loadUrl(imageUrl, customHeaders);
1440 // Add a `Download Image` entry.
1441 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1443 public boolean onMenuItemClick(MenuItem item) {
1444 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1445 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1446 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1451 // Add a `Copy URL` entry.
1452 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1454 public boolean onMenuItemClick(MenuItem item) {
1455 // Save the image URL in a `ClipData`.
1456 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1458 // Set the `ClipData` as the clipboard's primary clip.
1459 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1464 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1465 menu.add(R.string.cancel);
1471 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1472 // Get shortcutNameEditText from the alert dialog.
1473 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1475 // Create the bookmark shortcut based on formattedUrlString.
1476 Intent bookmarkShortcut = new Intent();
1477 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1478 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1480 // Place the bookmark shortcut on the home screen.
1481 Intent placeBookmarkShortcut = new Intent();
1482 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1483 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1484 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1485 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1486 sendBroadcast(placeBookmarkShortcut);
1490 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1491 // Download the image if it has an HTTP or HTTPS URI.
1492 if (imageUrl.startsWith("http")) {
1493 // Get a handle for the system `DOWNLOAD_SERVICE`.
1494 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1496 // Parse `imageUrl`.
1497 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1499 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1500 if (firstPartyCookiesEnabled) {
1501 // Get the cookies for `imageUrl`.
1502 String cookies = cookieManager.getCookie(imageUrl);
1504 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1505 downloadRequest.addRequestHeader("Cookie", cookies);
1508 // Get the file name from `dialogFragment`.
1509 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1510 String imageName = downloadImageNameEditText.getText().toString();
1512 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1513 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1514 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1515 } else { // Only set the title using `imageName`.
1516 downloadRequest.setTitle(imageName);
1519 // Allow `MediaScanner` to index the download if it is a media file.
1520 downloadRequest.allowScanningByMediaScanner();
1522 // Add the URL as the description for the download.
1523 downloadRequest.setDescription(imageUrl);
1525 // Show the download notification after the download is completed.
1526 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1528 // Initiate the download.
1529 downloadManager.enqueue(downloadRequest);
1530 } else { // The image is not an HTTP or HTTPS URI.
1531 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1536 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1537 // Download the file if it has an HTTP or HTTPS URI.
1538 if (downloadUrl.startsWith("http")) {
1540 // Get a handle for the system `DOWNLOAD_SERVICE`.
1541 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1543 // Parse `downloadUrl`.
1544 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1546 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
1547 if (firstPartyCookiesEnabled) {
1548 // Get the cookies for `downloadUrl`.
1549 String cookies = cookieManager.getCookie(downloadUrl);
1551 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1552 downloadRequest.addRequestHeader("Cookie", cookies);
1555 // Get the file name from `dialogFragment`.
1556 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1557 String fileName = downloadFileNameEditText.getText().toString();
1559 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1560 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1561 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1562 } else { // Only set the title using `fileName`.
1563 downloadRequest.setTitle(fileName);
1566 // Allow `MediaScanner` to index the download if it is a media file.
1567 downloadRequest.allowScanningByMediaScanner();
1569 // Add the URL as the description for the download.
1570 downloadRequest.setDescription(downloadUrl);
1572 // Show the download notification after the download is completed.
1573 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1575 // Initiate the download.
1576 downloadManager.enqueue(downloadRequest);
1577 } else { // The download is not an HTTP or HTTPS URI.
1578 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1582 public void viewSslCertificate(View view) {
1583 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1584 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1585 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1589 public void onSslErrorCancel() {
1590 sslErrorHandler.cancel();
1594 public void onSslErrorProceed() {
1595 sslErrorHandler.proceed();
1599 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1600 // Load the history entry.
1601 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1605 public void onClearHistory() {
1606 // Clear the history.
1607 mainWebView.clearHistory();
1610 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1612 public void onBackPressed() {
1613 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1614 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1615 drawerLayout.closeDrawer(GravityCompat.START);
1617 // Load the previous URL if available.
1618 if (mainWebView.canGoBack()) {
1619 mainWebView.goBack();
1621 // Pass `onBackPressed()` to the system.
1622 super.onBackPressed();
1628 public void onPause() {
1629 // Pause `mainWebView`.
1630 mainWebView.onPause();
1632 // Stop all JavaScript.
1633 mainWebView.pauseTimers();
1635 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1636 if (BuildConfig.FLAVOR.contentEquals("free")) {
1637 BannerAd.pauseAd(adView);
1644 public void onResume() {
1647 // Resume JavaScript (if enabled).
1648 mainWebView.resumeTimers();
1650 // Resume `mainWebView`.
1651 mainWebView.onResume();
1653 // Resume the adView for the free flavor.
1654 if (BuildConfig.FLAVOR.contentEquals("free")) {
1655 BannerAd.resumeAd(adView);
1660 public void onRestart() {
1663 // Apply the settings from shared preferences, which might have been changed in `Settings`.
1666 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1667 updatePrivacyIcons(true);
1671 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1672 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1673 String unformattedUrlString = urlTextBox.getText().toString().trim();
1675 URL unformattedUrl = null;
1676 Uri.Builder formattedUri = new Uri.Builder();
1678 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1679 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1680 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1681 if (!unformattedUrlString.startsWith("http")) {
1682 unformattedUrlString = "http://" + unformattedUrlString;
1685 // 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.
1687 unformattedUrl = new URL(unformattedUrlString);
1688 } catch (MalformedURLException e) {
1689 e.printStackTrace();
1692 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1693 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1694 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1695 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1696 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1697 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1699 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1700 formattedUrlString = formattedUri.build().toString();
1702 // Sanitize the search input and convert it to a DuckDuckGo search.
1703 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1705 // Use the correct search URL.
1706 if (javaScriptEnabled) { // JavaScript is enabled.
1707 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1708 } else { // JavaScript is disabled.
1709 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1713 mainWebView.loadUrl(formattedUrlString, customHeaders);
1715 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1716 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1719 public void findPreviousOnPage(View view) {
1720 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
1721 mainWebView.findNext(false);
1724 public void findNextOnPage(View view) {
1725 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
1726 mainWebView.findNext(true);
1729 public void closeFindOnPage(View view) {
1730 // Delete the contents of `find_on_page_edittext`.
1731 findOnPageEditText.setText(null);
1733 // Clear the highlighted phrases.
1734 mainWebView.clearMatches();
1736 // Hide the Find on Page `RelativeLayout`.
1737 findOnPageLinearLayout.setVisibility(View.GONE);
1739 // Show the URL app bar.
1740 supportAppBar.setVisibility(View.VISIBLE);
1742 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1743 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1746 private void applySettings() {
1747 // Get the shared preference values. `this` references the current context.
1748 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1750 // Store the values from `sharedPreferences` in variables.
1751 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
1752 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1753 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1754 String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1755 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1756 String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1757 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1758 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1759 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1760 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
1761 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
1762 boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1763 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
1764 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
1765 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
1767 // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1768 if (javaScriptEnabled == null) { // If `javaScriptEnabled` is null the program is just starting.
1769 // Get the values from `sharedPreferences`.
1770 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1771 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1772 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1773 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1774 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1776 // Apply the default settings.
1777 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1778 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1779 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1780 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1781 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1783 // Set third-party cookies status if API >= 21.
1784 if (Build.VERSION.SDK_INT >= 21) {
1785 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1789 // Apply the other settings from `sharedPreferences`.
1790 homepage = homepageString;
1791 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1793 // Set the user agent initial status.
1794 switch (userAgentString) {
1795 case "Default user agent":
1796 // Set the user agent to `""`, which uses the default value.
1797 mainWebView.getSettings().setUserAgentString("");
1800 case "Custom user agent":
1801 // Set the custom user agent.
1802 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1806 // Use the selected user agent.
1807 mainWebView.getSettings().setUserAgentString(userAgentString);
1811 // Set JavaScript disabled search.
1812 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1813 javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1814 } else { // Use the string from the pre-built list.
1815 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1818 // Set JavaScript enabled search.
1819 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1820 javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1821 } else { // Use the string from the pre-built list.
1822 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1825 // Set Do Not Track status.
1826 if (doNotTrackEnabled) {
1827 customHeaders.put("DNT", "1");
1829 customHeaders.remove("DNT");
1832 // Set Orbot proxy status.
1833 if (proxyThroughOrbot) {
1834 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
1835 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1836 } else { // Reset the proxy to default. The host is `""` and the port is `"0"`.
1837 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1840 // If we are in full screen mode update the `SYSTEM_UI` flags.
1841 if (inFullScreenBrowsingMode) {
1842 if (hideSystemBarsOnFullscreen) { // Hide everything.
1843 // Remove the translucent navigation setting if it is currently flagged.
1844 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1846 // Remove the translucent status bar overlay.
1847 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1849 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1850 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1852 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1853 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1854 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1856 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1857 } else { // Hide everything except the status and navigation bars.
1858 // Add the translucent status flag if it is unset.
1859 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1861 if (translucentNavigationBarOnFullscreen) {
1862 // Set the navigation bar to be translucent.
1863 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1865 // Set the navigation bar to be black.
1866 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1872 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
1873 // Get handles for the icons.
1874 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1875 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1876 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1877 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1879 // Update `privacyIcon`.
1880 if (javaScriptEnabled) { // JavaScript is enabled.
1881 privacyIcon.setIcon(R.drawable.javascript_enabled);
1882 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1883 privacyIcon.setIcon(R.drawable.warning);
1884 } else { // All the dangerous features are disabled.
1885 privacyIcon.setIcon(R.drawable.privacy_mode);
1888 // Update `firstPartyCookiesIcon`.
1889 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1890 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1891 } else { // First-party cookies are disabled.
1892 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1895 // Update `domStorageIcon`.
1896 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
1897 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1898 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
1899 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1900 } else { // JavaScript is disabled, so DOM storage is ghosted.
1901 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1904 // Update `formDataIcon`.
1905 if (saveFormDataEnabled) { // Form data is enabled.
1906 formDataIcon.setIcon(R.drawable.form_data_enabled);
1907 } else { // Form data is disabled.
1908 formDataIcon.setIcon(R.drawable.form_data_disabled);
1911 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
1912 if (runInvalidateOptionsMenu) {
1913 ActivityCompat.invalidateOptionsMenu(this);