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;
22 import android.annotation.SuppressLint;
23 import android.app.Activity;
24 import android.app.DialogFragment;
25 import android.app.DownloadManager;
26 import android.content.Intent;
27 import android.content.SharedPreferences;
28 import android.content.res.Configuration;
29 import android.graphics.Bitmap;
30 import android.graphics.drawable.BitmapDrawable;
31 import android.graphics.drawable.Drawable;
32 import android.net.Uri;
33 import android.net.http.SslError;
34 import android.os.Build;
35 import android.os.Bundle;
36 import android.preference.PreferenceManager;
37 import android.support.design.widget.NavigationView;
38 import android.support.design.widget.Snackbar;
39 import android.support.v4.app.ActivityCompat;
40 import android.support.v4.content.ContextCompat;
41 import android.support.v4.view.GravityCompat;
42 import android.support.v4.widget.DrawerLayout;
43 import android.support.v4.widget.SwipeRefreshLayout;
44 import android.support.v7.app.ActionBar;
45 import android.support.v7.app.ActionBarDrawerToggle;
46 import android.support.v7.app.AppCompatActivity;
47 import android.support.v7.widget.Toolbar;
48 import android.util.Patterns;
49 import android.view.KeyEvent;
50 import android.view.Menu;
51 import android.view.MenuItem;
52 import android.view.View;
53 import android.view.inputmethod.InputMethodManager;
54 import android.webkit.CookieManager;
55 import android.webkit.DownloadListener;
56 import android.webkit.SslErrorHandler;
57 import android.webkit.WebChromeClient;
58 import android.webkit.WebStorage;
59 import android.webkit.WebView;
60 import android.webkit.WebViewClient;
61 import android.webkit.WebViewDatabase;
62 import android.widget.EditText;
63 import android.widget.FrameLayout;
64 import android.widget.ImageView;
65 import android.widget.ProgressBar;
67 import java.io.UnsupportedEncodingException;
68 import java.net.MalformedURLException;
70 import java.net.URLEncoder;
71 import java.util.HashMap;
74 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
75 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
76 SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener {
77 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `BookmarksActivity`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
78 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
79 public static Bitmap favoriteIcon;
81 // `privacyBrowserActivity` is public static so it can be accessed from `SettingsFragment`.
82 // It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`,
83 public static Activity privacyBrowserActivity;
85 // `mainWebView` is public static so it can be accessed from `SettingsFragment`.
86 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, and `loadUrlFromTextBox()`.
87 public static WebView mainWebView;
89 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`.
90 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
91 public static String formattedUrlString;
93 // `mainMenu` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreateOptionsMenu()` and `onOptionsItemSelected()`.
94 public static Menu mainMenu;
96 // `cookieManager` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
97 public static CookieManager cookieManager;
99 // `javaScriptEnabled` is public static so it can be accessed from `SettingsFragment`.
100 // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
101 public static boolean javaScriptEnabled;
103 // `firstPartyCookiesEnabled` is public static so it can be accessed from `SettingsFragment`.
104 // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
105 public static boolean firstPartyCookiesEnabled;
107 // `thirdPartyCookiesEnables` is public static so it can be accessed from `SettingsFragment`.
108 // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
109 public static boolean thirdPartyCookiesEnabled;
111 // `domStorageEnabled` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`.
112 public static boolean domStorageEnabled;
114 // `saveFormDataEnabled` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`.
115 public static boolean saveFormDataEnabled;
117 // `javaScriptDisabledSearchURL` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()` and `loadURLFromTextBox()`.
118 public static String javaScriptDisabledSearchURL;
120 // `javaScriptEnabledSearchURL` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()` and `loadURLFromTextBox()`.
121 public static String javaScriptEnabledSearchURL;
123 // `homepage` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()` and `onOptionsItemSelected()`.
124 public static String homepage;
126 // `swipeToRefresh` is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
127 public static SwipeRefreshLayout swipeToRefresh;
129 // `swipeToRefreshEnabled` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`.
130 public static boolean swipeToRefreshEnabled;
132 // `customHeader` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
133 public static Map<String, String> customHeaders = new HashMap<String, String>();
137 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
138 private ActionBarDrawerToggle drawerToggle;
140 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
141 private DrawerLayout drawerLayout;
143 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
144 private EditText urlTextBox;
146 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
149 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
150 private SslErrorHandler sslErrorHandler;
152 // `sharedPreferences` is used in `onCreate()` and `onCreateOptionsMenu()`.
153 SharedPreferences sharedPreferences;
156 // 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.
157 @SuppressLint("SetJavaScriptEnabled")
158 protected void onCreate(Bundle savedInstanceState) {
159 super.onCreate(savedInstanceState);
160 setContentView(R.layout.main_coordinatorlayout);
162 // We need a handle for the activity, which is accessed from `SettingsFragment` and fed into `updatePrivacyIcons()`.
163 privacyBrowserActivity = this;
165 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
166 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
167 setSupportActionBar(supportAppBar);
168 final ActionBar appBar = getSupportActionBar();
170 // This is needed to get rid of the Android Studio warning that appBar might be null.
171 assert appBar != null;
173 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
174 appBar.setCustomView(R.layout.url_bar);
175 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
177 // Set the "go" button on the keyboard to load the URL in urlTextBox.
178 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
179 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
180 public boolean onKey(View v, int keyCode, KeyEvent event) {
181 // If the event is a key-down event on the "enter" button, load the URL.
182 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
183 // Load the URL into the mainWebView and consume the event.
185 loadUrlFromTextBox();
186 } catch (UnsupportedEncodingException e) {
189 // If the enter key was pressed, consume the event.
192 // If any other key was pressed, do not consume the event.
198 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
200 // Implement swipe to refresh
201 swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
202 assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null.
203 swipeToRefresh.setColorSchemeResources(R.color.blue);
204 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
206 public void onRefresh() {
207 mainWebView.reload();
211 mainWebView = (WebView) findViewById(R.id.mainWebView);
213 // Create the navigation drawer.
214 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
215 // The DrawerTitle identifies the drawer in accessibility mode.
216 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
218 // Listen for touches on the navigation menu.
219 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
220 assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null.
221 navigationView.setNavigationItemSelectedListener(this);
223 // drawerToggle creates the hamburger icon at the start of the AppBar.
224 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
226 mainWebView.setWebViewClient(new WebViewClient() {
227 // shouldOverrideUrlLoading makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
229 public boolean shouldOverrideUrlLoading(WebView view, String url) {
230 // Use an external email program if the link begins with "mailto:".
231 if (url.startsWith("mailto:")) {
232 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
233 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
235 // Parse the url and set it as the data for the `Intent`.
236 emailIntent.setData(Uri.parse(url));
238 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
239 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
242 startActivity(emailIntent);
244 } else { // Load the URL in Privacy Browser.
245 mainWebView.loadUrl(url, customHeaders);
250 // Update the URL in urlTextBox when the page starts to load.
252 public void onPageStarted(WebView view, String url, Bitmap favicon) {
253 urlTextBox.setText(url);
256 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
258 public void onPageFinished(WebView view, String url) {
259 formattedUrlString = url;
261 // Only update urlTextBox if the user is not typing in it.
262 if (!urlTextBox.hasFocus()) {
263 urlTextBox.setText(formattedUrlString);
267 // Handle SSL Certificate errors.
269 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
270 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
271 sslErrorHandler = handler;
273 // Display the SSL error `AlertDialog`.
274 DialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
275 sslCertificateErrorDialogFragment.show(getFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
279 mainWebView.setWebChromeClient(new WebChromeClient() {
280 // Update the progress bar when a page is loading.
282 public void onProgressChanged(WebView view, int progress) {
283 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
284 progressBar.setProgress(progress);
285 if (progress < 100) {
286 progressBar.setVisibility(View.VISIBLE);
288 progressBar.setVisibility(View.GONE);
290 //Stop the SwipeToRefresh indicator if it is running
291 swipeToRefresh.setRefreshing(false);
295 // Set the favorite icon when it changes.
297 public void onReceivedIcon(WebView view, Bitmap icon) {
298 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
301 // Place the favorite icon in the appBar.
302 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
303 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
306 // Enter full screen video
308 public void onShowCustomView(View view, CustomViewCallback callback) {
311 // Show the fullScreenVideoFrameLayout.
312 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
313 fullScreenVideoFrameLayout.addView(view);
314 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
316 // Hide the mainWebView.
317 mainWebView.setVisibility(View.GONE);
319 // Hide the ad if this is the free flavor.
320 BannerAd.hideAd(adView);
322 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
323 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
324 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
326 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
329 // Exit full screen video
330 public void onHideCustomView() {
333 // Show the mainWebView.
334 mainWebView.setVisibility(View.VISIBLE);
336 // Show the ad if this is the free flavor.
337 BannerAd.showAd(adView);
339 // Hide the fullScreenVideoFrameLayout.
340 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
341 fullScreenVideoFrameLayout.removeAllViews();
342 fullScreenVideoFrameLayout.setVisibility(View.GONE);
346 // Allow the downloading of files.
347 mainWebView.setDownloadListener(new DownloadListener() {
349 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
350 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
351 DialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
352 downloadFileDialogFragment.show(getFragmentManager(), getResources().getString(R.string.file_download));
356 // Allow pinch to zoom.
357 mainWebView.getSettings().setBuiltInZoomControls(true);
359 // Hide zoom controls.
360 mainWebView.getSettings().setDisplayZoomControls(false);
363 // Initialize the default preference values the first time the program is run.
364 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
366 // Get the shared preference values.
367 sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
369 // Set JavaScript initial status. The default value is false.
370 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
371 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
373 // Initialize cookieManager.
374 cookieManager = CookieManager.getInstance();
376 // Set cookies initial status. The default value is false.
377 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
378 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
380 // Set third-party cookies initial status if API >= 21. The default value is false.
381 if (Build.VERSION.SDK_INT >= 21) {
382 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
383 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
386 // Set DOM storage initial status. The default value is false.
387 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
388 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
390 // Set the saved form data initial status. The default is false.
391 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
392 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
394 // Set the user agent initial status.
395 String userAgentString = sharedPreferences.getString("user_agent", "Default user agent");
396 switch (userAgentString) {
397 case "Default user agent":
401 case "Custom user agent":
402 // Set the custom user agent on mainWebView, The default is "PrivacyBrowser/1.0".
403 mainWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0"));
407 // Set the selected user agent on mainWebView. The default is "PrivacyBrowser/1.0".
408 mainWebView.getSettings().setUserAgentString(sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0"));
412 // Set the initial string for JavaScript disabled search.
413 if (sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=").equals("Custom URL")) {
414 // Get the custom URL string. The default is "".
415 javaScriptDisabledSearchURL = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
417 // Use the string from javascript_disabled_search.
418 javaScriptDisabledSearchURL = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
421 // Set the initial string for JavaScript enabled search.
422 if (sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=").equals("Custom URL")) {
423 // Get the custom URL string. The default is "".
424 javaScriptEnabledSearchURL = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
426 // Use the string from javascript_enabled_search.
427 javaScriptEnabledSearchURL = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
431 // Set the homepage initial status. The default value is `https://www.duckduckgo.com`.
432 homepage = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
434 // Set the font size initial status. the default value is `100`.
435 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
436 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
438 // Set the swipe to refresh initial status. The default is `true`.
439 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", true);
440 swipeToRefresh.setEnabled(swipeToRefreshEnabled);
443 // 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).
444 customHeaders.put("X-Requested-With", "");
446 // Set Do Not Track. The default is true.
447 if (sharedPreferences.getBoolean("do_not_track", true)) {
448 customHeaders.put("DNT", "1");
452 // Get the intent information that started the app.
453 final Intent intent = getIntent();
455 if (intent.getData() != null) {
456 // Get the intent data and convert it to a string.
457 final Uri intentUriData = intent.getData();
458 formattedUrlString = intentUriData.toString();
461 // If formattedUrlString is null assign the homepage to it.
462 if (formattedUrlString == null) {
463 formattedUrlString = homepage;
466 // Load the initial website.
467 mainWebView.loadUrl(formattedUrlString, customHeaders);
469 // If the favorite icon is null, load the default.
470 if (favoriteIcon == null) {
471 // We have to use `ContextCompat` until API >= 21.
472 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
473 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
474 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
477 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
478 adView = findViewById(R.id.adView);
479 BannerAd.requestAd(adView);
484 protected void onNewIntent(Intent intent) {
485 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
488 if (intent.getData() != null) {
489 // Get the intent data and convert it to a string.
490 final Uri intentUriData = intent.getData();
491 formattedUrlString = intentUriData.toString();
494 // Close the navigation drawer if it is open.
495 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
496 drawerLayout.closeDrawer(GravityCompat.START);
500 mainWebView.loadUrl(formattedUrlString, customHeaders);
502 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
503 mainWebView.requestFocus();
507 public boolean onCreateOptionsMenu(Menu menu) {
508 // Inflate the menu; this adds items to the action bar if it is present.
509 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
511 // Set mainMenu so it can be used by onOptionsItemSelected.
514 // Set the initial status of the privacy icon.
515 updatePrivacyIcons(privacyBrowserActivity);
517 // Get handles for the menu items.
518 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
519 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
520 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
521 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
523 // Set the initial status of the menu item checkboxes.
524 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
525 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
526 toggleDomStorage.setChecked(domStorageEnabled);
527 toggleSaveFormData.setChecked(saveFormDataEnabled);
529 // Set the status of the additional app bar icons. The default is `false`.
530 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
531 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
532 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
533 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
534 } else { //Do not display the additional icons.
535 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
536 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
537 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
544 public boolean onPrepareOptionsMenu(Menu menu) {
545 // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
546 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
547 if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
548 toggleThirdPartyCookies.setEnabled(true);
550 toggleThirdPartyCookies.setEnabled(false);
553 // Enable DOM Storage if JavaScript is enabled.
554 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
555 toggleDomStorage.setEnabled(javaScriptEnabled);
557 // Enable Clear Cookies if there are any.
558 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
559 clearCookies.setEnabled(cookieManager.hasCookies());
561 // Enable Clear Form Data is there is any.
562 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
563 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
564 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
566 // Initialize font size variables.
567 int fontSize = mainWebView.getSettings().getTextZoom();
568 String fontSizeTitle;
569 MenuItem selectedFontSizeMenuItem;
571 // Prepare the font size title and current size menu item.
574 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
575 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
579 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
580 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
584 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
585 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
589 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
590 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
594 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
595 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
599 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
600 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
604 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
605 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
609 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
610 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
614 // Set the font size title and select the current size menu item.
615 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
616 fontSizeMenuItem.setTitle(fontSizeTitle);
617 selectedFontSizeMenuItem.setChecked(true);
619 // Only show `Refresh` if `swipeToRefresh` is disabled.
620 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
621 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
623 // Run all the other default commands.
624 super.onPrepareOptionsMenu(menu);
626 // `return true` displays the menu.
631 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
632 @SuppressLint("SetJavaScriptEnabled")
633 // removeAllCookies is deprecated, but it is required for API < 21.
634 @SuppressWarnings("deprecation")
635 public boolean onOptionsItemSelected(MenuItem menuItem) {
636 int menuItemId = menuItem.getItemId();
638 // Set the commands that relate to the menu entries.
639 switch (menuItemId) {
640 case R.id.toggleJavaScript:
641 // Switch the status of javaScriptEnabled.
642 javaScriptEnabled = !javaScriptEnabled;
644 // Apply the new JavaScript status.
645 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
647 // Update the privacy icon.
648 updatePrivacyIcons(privacyBrowserActivity);
650 // Display a `Snackbar`.
651 if (javaScriptEnabled) {
652 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
654 if (firstPartyCookiesEnabled) {
655 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
657 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
661 // Reload the WebView.
662 mainWebView.reload();
665 case R.id.toggleFirstPartyCookies:
666 // Switch the status of firstPartyCookiesEnabled.
667 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
669 // Update the menu checkbox.
670 menuItem.setChecked(firstPartyCookiesEnabled);
672 // Apply the new cookie status.
673 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
675 // Update the privacy icon.
676 updatePrivacyIcons(privacyBrowserActivity);
678 // Display a `Snackbar`.
679 if (firstPartyCookiesEnabled) {
680 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
682 if (javaScriptEnabled) {
683 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
685 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
689 // Reload the WebView.
690 mainWebView.reload();
693 case R.id.toggleThirdPartyCookies:
694 if (Build.VERSION.SDK_INT >= 21) {
695 // Switch the status of thirdPartyCookiesEnabled.
696 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
698 // Update the menu checkbox.
699 menuItem.setChecked(thirdPartyCookiesEnabled);
701 // Apply the new cookie status.
702 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
704 // Display a `Snackbar`.
705 if (thirdPartyCookiesEnabled) {
706 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
708 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
711 // Reload the WebView.
712 mainWebView.reload();
713 } // Else do nothing because SDK < 21.
716 case R.id.toggleDomStorage:
717 // Switch the status of domStorageEnabled.
718 domStorageEnabled = !domStorageEnabled;
720 // Update the menu checkbox.
721 menuItem.setChecked(domStorageEnabled);
723 // Apply the new DOM Storage status.
724 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
726 // Display a `Snackbar`.
727 if (domStorageEnabled) {
728 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
730 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
733 // Reload the WebView.
734 mainWebView.reload();
737 case R.id.toggleSaveFormData:
738 // Switch the status of saveFormDataEnabled.
739 saveFormDataEnabled = !saveFormDataEnabled;
741 // Update the menu checkbox.
742 menuItem.setChecked(saveFormDataEnabled);
744 // Apply the new form data status.
745 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
747 // Display a `Snackbar`.
748 if (saveFormDataEnabled) {
749 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
751 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
754 // Reload the WebView.
755 mainWebView.reload();
758 case R.id.clearCookies:
759 if (Build.VERSION.SDK_INT < 21) {
760 cookieManager.removeAllCookie();
762 cookieManager.removeAllCookies(null);
764 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
767 case R.id.clearDomStorage:
768 WebStorage webStorage = WebStorage.getInstance();
769 webStorage.deleteAllData();
770 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
773 case R.id.clearFormData:
774 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
775 mainWebViewDatabase.clearFormData();
776 mainWebView.reload();
779 case R.id.fontSizeFiftyPercent:
780 mainWebView.getSettings().setTextZoom(50);
783 case R.id.fontSizeSeventyFivePercent:
784 mainWebView.getSettings().setTextZoom(75);
787 case R.id.fontSizeOneHundredPercent:
788 mainWebView.getSettings().setTextZoom(100);
791 case R.id.fontSizeOneHundredTwentyFivePercent:
792 mainWebView.getSettings().setTextZoom(125);
795 case R.id.fontSizeOneHundredFiftyPercent:
796 mainWebView.getSettings().setTextZoom(150);
799 case R.id.fontSizeOneHundredSeventyFivePercent:
800 mainWebView.getSettings().setTextZoom(175);
803 case R.id.fontSizeTwoHundredPercent:
804 mainWebView.getSettings().setTextZoom(200);
808 Intent shareIntent = new Intent();
809 shareIntent.setAction(Intent.ACTION_SEND);
810 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
811 shareIntent.setType("text/plain");
812 startActivity(Intent.createChooser(shareIntent, "Share URL"));
815 case R.id.addToHomescreen:
816 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `@string/create_shortcut`.
817 DialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
818 createHomeScreenShortcutDialogFragment.show(getFragmentManager(), getResources().getString(R.string.create_shortcut));
820 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
824 mainWebView.reload();
828 // Don't consume the event.
829 return super.onOptionsItemSelected(menuItem);
834 // removeAllCookies is deprecated, but it is required for API < 21.
835 @SuppressWarnings("deprecation")
836 public boolean onNavigationItemSelected(MenuItem menuItem) {
837 int menuItemId = menuItem.getItemId();
839 switch (menuItemId) {
841 mainWebView.loadUrl(homepage, customHeaders);
845 if (mainWebView.canGoBack()) {
846 mainWebView.goBack();
851 if (mainWebView.canGoForward()) {
852 mainWebView.goForward();
857 // Launch BookmarksActivity.
858 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
859 startActivity(bookmarksIntent);
863 // Launch the system Download Manager.
864 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
866 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
867 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
869 startActivity(downloadManagerIntent);
873 // Launch `SettingsActivity`.
874 Intent settingsIntent = new Intent(this, SettingsActivity.class);
875 startActivity(settingsIntent);
879 // Launch `GuideActivity`.
880 Intent guideIntent = new Intent(this, GuideActivity.class);
881 startActivity(guideIntent);
885 // Launch `AboutActivity`.
886 Intent aboutIntent = new Intent(this, AboutActivity.class);
887 startActivity(aboutIntent);
890 case R.id.clearAndExit:
891 // Clear cookies. The commands changed slightly in API 21.
892 if (Build.VERSION.SDK_INT >= 21) {
893 cookieManager.removeAllCookies(null);
895 cookieManager.removeAllCookie();
898 // Clear DOM storage.
899 WebStorage domStorage = WebStorage.getInstance();
900 domStorage.deleteAllData();
903 WebViewDatabase formData = WebViewDatabase.getInstance(this);
904 formData.clearFormData();
906 // Clear cache. The argument of "true" includes disk files.
907 mainWebView.clearCache(true);
909 // Clear the back/forward history.
910 mainWebView.clearHistory();
912 // Clear any SSL certificate preferences.
913 MainWebViewActivity.mainWebView.clearSslPreferences();
915 // Clear `formattedUrlString`.
916 formattedUrlString = null;
918 // Clear `customHeaders`.
919 customHeaders.clear();
921 // Destroy the internal state of the webview.
922 mainWebView.destroy();
924 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
925 if (Build.VERSION.SDK_INT >= 21) {
926 finishAndRemoveTask();
936 // Close the navigation drawer.
937 drawerLayout.closeDrawer(GravityCompat.START);
942 public void onPostCreate(Bundle savedInstanceState) {
943 super.onPostCreate(savedInstanceState);
945 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
946 drawerToggle.syncState();
950 public void onConfigurationChanged(Configuration newConfig) {
951 super.onConfigurationChanged(newConfig);
953 // Reload the ad if this is the free flavor.
954 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
956 // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
957 adView = findViewById(R.id.adView);
959 // `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
960 invalidateOptionsMenu();
964 public void onCreateHomeScreenShortcut(DialogFragment dialogFragment) {
965 // Get shortcutNameEditText from the alert dialog.
966 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
968 // Create the bookmark shortcut based on formattedUrlString.
969 Intent bookmarkShortcut = new Intent();
970 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
971 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
973 // Place the bookmark shortcut on the home screen.
974 Intent placeBookmarkShortcut = new Intent();
975 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
976 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
977 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
978 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
979 sendBroadcast(placeBookmarkShortcut);
983 public void onDownloadFile(DialogFragment dialogFragment, String downloadUrl) {
984 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
985 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
987 // Get the file name from `dialogFragment`.
988 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
989 String fileName = downloadFileNameEditText.getText().toString();
991 // Set the download save in the the `DIRECTORY_DOWNLOADS`using `fileName`.
992 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
993 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
995 // Allow `MediaScanner` to index the download if it is a media file.
996 downloadRequest.allowScanningByMediaScanner();
998 // Add the URL as the description for the download.
999 downloadRequest.setDescription(downloadUrl);
1001 // Show the download notification after the download is completed.
1002 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1004 // Initiate the download and display a Snackbar.
1005 downloadManager.enqueue(downloadRequest);
1008 public void viewSslCertificate(View view) {
1009 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1010 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1011 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1015 public void onSslErrorCancel() {
1016 sslErrorHandler.cancel();
1020 public void onSslErrorProceed() {
1021 sslErrorHandler.proceed();
1024 // Override onBackPressed to handle the navigation drawer and mainWebView.
1026 public void onBackPressed() {
1027 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
1029 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1030 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1031 drawerLayout.closeDrawer(GravityCompat.START);
1033 // Load the previous URL if available.
1034 assert mainWebView != null; //This assert removes the incorrect warning in Android Studio on the following line that mainWebView might be null.
1035 if (mainWebView.canGoBack()) {
1036 mainWebView.goBack();
1038 // Pass onBackPressed to the system.
1039 super.onBackPressed();
1045 public void onPause() {
1046 // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
1047 BannerAd.pauseAd(adView);
1053 public void onResume() {
1056 // We need to resume the adView for the free flavor.
1057 BannerAd.resumeAd(adView);
1060 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1061 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1062 String unformattedUrlString = urlTextBox.getText().toString().trim();
1064 URL unformattedUrl = null;
1065 Uri.Builder formattedUri = new Uri.Builder();
1067 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1068 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1069 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1070 if (!unformattedUrlString.startsWith("http")) {
1071 unformattedUrlString = "http://" + unformattedUrlString;
1074 // 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.
1076 unformattedUrl = new URL(unformattedUrlString);
1077 } catch (MalformedURLException e) {
1078 e.printStackTrace();
1081 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1082 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1083 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1084 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1085 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1086 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1088 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1089 formattedUrlString = formattedUri.build().toString();
1091 // Sanitize the search input and convert it to a DuckDuckGo search.
1092 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1094 // Use the correct search URL based on javaScriptEnabled.
1095 if (javaScriptEnabled) {
1096 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1097 } else { // JavaScript is disabled.
1098 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1102 mainWebView.loadUrl(formattedUrlString, customHeaders);
1104 // Hides the keyboard so we can see the webpage.
1105 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
1106 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1109 public static void updatePrivacyIcons(Activity activity) {
1110 // Get handles for the icons.
1111 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1112 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1113 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1114 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1116 // Update `privacyIcon`.
1117 if (javaScriptEnabled) { // JavaScript is enabled.
1118 privacyIcon.setIcon(R.drawable.javascript_enabled);
1119 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1120 privacyIcon.setIcon(R.drawable.warning);
1121 } else { // All the dangerous features are disabled.
1122 privacyIcon.setIcon(R.drawable.privacy_mode);
1125 // Update `firstPartyCookiesIcon`.
1126 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1127 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1128 } else { // First-party cookies are disabled.
1129 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1132 // Update `domStorageIcon`.
1133 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage is enabled.
1134 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1135 } else if (javaScriptEnabled){ // JavaScript is enabled but DOM storage is disabled.
1136 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1137 } else { // JavaScript is disabled, so DOM storage is ghosted.
1138 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1141 // Update `formDataIcon`.
1142 if (saveFormDataEnabled) { // Form data is enabled.
1143 formDataIcon.setIcon(R.drawable.form_data_enabled);
1144 } else { // Form data is disabled.
1145 formDataIcon.setIcon(R.drawable.form_data_disabled);
1148 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
1149 ActivityCompat.invalidateOptionsMenu(activity);