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.os.Build;
34 import android.os.Bundle;
35 import android.preference.PreferenceManager;
36 import android.support.design.widget.NavigationView;
37 import android.support.design.widget.Snackbar;
38 import android.support.v4.content.ContextCompat;
39 import android.support.v4.view.GravityCompat;
40 import android.support.v4.widget.DrawerLayout;
41 import android.support.v4.widget.SwipeRefreshLayout;
42 import android.support.v7.app.ActionBar;
43 import android.support.v7.app.ActionBarDrawerToggle;
44 import android.support.v7.app.AppCompatActivity;
45 import android.support.v7.widget.Toolbar;
46 import android.util.Patterns;
47 import android.view.KeyEvent;
48 import android.view.Menu;
49 import android.view.MenuItem;
50 import android.view.View;
51 import android.view.inputmethod.InputMethodManager;
52 import android.webkit.CookieManager;
53 import android.webkit.DownloadListener;
54 import android.webkit.WebChromeClient;
55 import android.webkit.WebStorage;
56 import android.webkit.WebView;
57 import android.webkit.WebViewClient;
58 import android.webkit.WebViewDatabase;
59 import android.widget.EditText;
60 import android.widget.FrameLayout;
61 import android.widget.ImageView;
62 import android.widget.ProgressBar;
64 import java.io.UnsupportedEncodingException;
65 import java.net.MalformedURLException;
67 import java.net.URLEncoder;
68 import java.util.HashMap;
71 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
72 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
73 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `BookmarksActivity`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
74 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
75 public static Bitmap favoriteIcon;
77 // `mainWebView` is public static so it can be accessed from `SettingsFragment`.
78 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, and `loadUrlFromTextBox()`.
79 public static WebView mainWebView;
81 // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`.
82 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
83 public static String formattedUrlString;
85 // `mainMenu` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreateOptionsMenu()` and `onOptionsItemSelected()`.
86 public static Menu mainMenu;
88 // `cookieManager` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
89 public static CookieManager cookieManager;
91 // `javaScriptEnabled` is public static so it can be accessed from `SettingsFragment`.
92 // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
93 public static boolean javaScriptEnabled;
95 // `firstPartyCookiesEnabled` is public static so it can be accessed from `SettingsFragment`.
96 // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
97 public static boolean firstPartyCookiesEnabled;
99 // `thirdPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
100 public static boolean thirdPartyCookiesEnabled;
102 // `domStorageEnabled` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`.
103 public static boolean domStorageEnabled;
105 // `saveFormDataEnabled` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`.
106 public static boolean saveFormDataEnabled;
108 // `javaScriptDisabledSearchURL` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()` and `loadURLFromTextBox()`.
109 public static String javaScriptDisabledSearchURL;
111 // `javaScriptEnabledSearchURL` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()` and `loadURLFromTextBox()`.
112 public static String javaScriptEnabledSearchURL;
114 // `homepage` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()` and `onOptionsItemSelected()`.
115 public static String homepage;
117 // `swipeToRefresh` is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
118 public static SwipeRefreshLayout swipeToRefresh;
120 // `swipeToRefreshEnabled` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`.
121 public static boolean swipeToRefreshEnabled;
123 // `customHeader` is public static so it can be accessed from `BookmarksActivity`. It is also used in `onCreate()` and `loadUrlFromTextBox()`.
124 public static Map<String, String> customHeaders = new HashMap<String, String>();
128 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
129 private ActionBarDrawerToggle drawerToggle;
131 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
132 private DrawerLayout drawerLayout;
134 // `privacyIcon` is used in `onCreateOptionsMenu()` and `updatePrivacyIcon()`.
135 private MenuItem privacyIcon;
137 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
138 private EditText urlTextBox;
140 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
144 // 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.
145 @SuppressLint("SetJavaScriptEnabled")
146 protected void onCreate(Bundle savedInstanceState) {
147 super.onCreate(savedInstanceState);
148 setContentView(R.layout.main_coordinatorlayout);
150 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
151 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
152 setSupportActionBar(supportAppBar);
153 final ActionBar appBar = getSupportActionBar();
155 // This is needed to get rid of the Android Studio warning that appBar might be null.
156 assert appBar != null;
158 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
159 appBar.setCustomView(R.layout.url_bar);
160 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
162 // Set the "go" button on the keyboard to load the URL in urlTextBox.
163 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
164 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
165 public boolean onKey(View v, int keyCode, KeyEvent event) {
166 // If the event is a key-down event on the "enter" button, load the URL.
167 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
168 // Load the URL into the mainWebView and consume the event.
170 loadUrlFromTextBox();
171 } catch (UnsupportedEncodingException e) {
174 // If the enter key was pressed, consume the event.
177 // If any other key was pressed, do not consume the event.
183 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
185 // Implement swipe to refresh
186 swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
187 assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null.
188 swipeToRefresh.setColorSchemeResources(R.color.blue);
189 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
191 public void onRefresh() {
192 mainWebView.reload();
196 mainWebView = (WebView) findViewById(R.id.mainWebView);
198 // Create the navigation drawer.
199 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
200 // The DrawerTitle identifies the drawer in accessibility mode.
201 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
203 // Listen for touches on the navigation menu.
204 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
205 assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null.
206 navigationView.setNavigationItemSelectedListener(this);
208 // drawerToggle creates the hamburger icon at the start of the AppBar.
209 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
211 // 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).
212 customHeaders.put("X-Requested-With", "");
214 mainWebView.setWebViewClient(new WebViewClient() {
215 // shouldOverrideUrlLoading makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
217 public boolean shouldOverrideUrlLoading(WebView view, String url) {
218 // Use an external email program if the link begins with "mailto:".
219 if (url.startsWith("mailto:")) {
220 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
221 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
223 // Parse the url and set it as the data for the `Intent`.
224 emailIntent.setData(Uri.parse(url));
226 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
227 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
230 startActivity(emailIntent);
232 } else { // Load the URL in Privacy Browser.
233 mainWebView.loadUrl(url, customHeaders);
238 // Update the URL in urlTextBox when the page starts to load.
240 public void onPageStarted(WebView view, String url, Bitmap favicon) {
241 urlTextBox.setText(url);
244 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
246 public void onPageFinished(WebView view, String url) {
247 formattedUrlString = url;
249 // Only update urlTextBox if the user is not typing in it.
250 if (!urlTextBox.hasFocus()) {
251 urlTextBox.setText(formattedUrlString);
256 mainWebView.setWebChromeClient(new WebChromeClient() {
257 // Update the progress bar when a page is loading.
259 public void onProgressChanged(WebView view, int progress) {
260 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
261 progressBar.setProgress(progress);
262 if (progress < 100) {
263 progressBar.setVisibility(View.VISIBLE);
265 progressBar.setVisibility(View.GONE);
267 //Stop the SwipeToRefresh indicator if it is running
268 swipeToRefresh.setRefreshing(false);
272 // Set the favorite icon when it changes.
274 public void onReceivedIcon(WebView view, Bitmap icon) {
275 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
278 // Place the favorite icon in the appBar.
279 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
280 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
283 // Enter full screen video
285 public void onShowCustomView(View view, CustomViewCallback callback) {
288 // Show the fullScreenVideoFrameLayout.
289 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
290 fullScreenVideoFrameLayout.addView(view);
291 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
293 // Hide the mainWebView.
294 mainWebView.setVisibility(View.GONE);
296 // Hide the ad if this is the free flavor.
297 BannerAd.hideAd(adView);
299 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
300 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
301 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
303 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
306 // Exit full screen video
307 public void onHideCustomView() {
310 // Show the mainWebView.
311 mainWebView.setVisibility(View.VISIBLE);
313 // Show the ad if this is the free flavor.
314 BannerAd.showAd(adView);
316 // Hide the fullScreenVideoFrameLayout.
317 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
318 fullScreenVideoFrameLayout.removeAllViews();
319 fullScreenVideoFrameLayout.setVisibility(View.GONE);
323 // Allow the downloading of files.
324 mainWebView.setDownloadListener(new DownloadListener() {
325 // Launch the Android download manager when a link leads to a download.
327 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
328 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
329 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
331 // Add the URL as the description for the download.
332 requestUri.setDescription(url);
334 // Show the download notification after the download is completed.
335 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
337 // Initiate the download and display a Snackbar.
338 downloadManager.enqueue(requestUri);
339 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
343 // Allow pinch to zoom.
344 mainWebView.getSettings().setBuiltInZoomControls(true);
346 // Hide zoom controls.
347 mainWebView.getSettings().setDisplayZoomControls(false);
350 // Initialize the default preference values the first time the program is run.
351 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
353 // Get the shared preference values.
354 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
356 // Set JavaScript initial status. The default value is false.
357 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
358 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
360 // Initialize cookieManager.
361 cookieManager = CookieManager.getInstance();
363 // Set cookies initial status. The default value is false.
364 firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false);
365 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
367 // Set third-party cookies initial status if API >= 21. The default value is false.
368 if (Build.VERSION.SDK_INT >= 21) {
369 thirdPartyCookiesEnabled = savedPreferences.getBoolean("third_party_cookies_enabled", false);
370 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
373 // Set DOM storage initial status. The default value is false.
374 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
375 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
377 // Set the saved form data initial status. The default is false.
378 saveFormDataEnabled = savedPreferences.getBoolean("save_form_data_enabled", false);
379 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
381 // Set the user agent initial status.
382 String userAgentString = savedPreferences.getString("user_agent", "Default user agent");
383 switch (userAgentString) {
384 case "Default user agent":
388 case "Custom user agent":
389 // Set the custom user agent on mainWebView, The default is "PrivacyBrowser/1.0".
390 mainWebView.getSettings().setUserAgentString(savedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0"));
394 // Set the selected user agent on mainWebView. The default is "PrivacyBrowser/1.0".
395 mainWebView.getSettings().setUserAgentString(savedPreferences.getString("user_agent", "PrivacyBrowser/1.0"));
399 // Set the initial string for JavaScript disabled search.
400 if (savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=").equals("Custom URL")) {
401 // Get the custom URL string. The default is "".
402 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search_custom_url", "");
404 // Use the string from javascript_disabled_search.
405 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
408 // Set the initial string for JavaScript enabled search.
409 if (savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=").equals("Custom URL")) {
410 // Get the custom URL string. The default is "".
411 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search_custom_url", "");
413 // Use the string from javascript_enabled_search.
414 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
418 // Set homepage initial status. The default value is "https://www.duckduckgo.com".
419 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
421 // Set swipe to refresh initial status. The default is true.
422 swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
423 swipeToRefresh.setEnabled(swipeToRefreshEnabled);
426 // Get the intent information that started the app.
427 final Intent intent = getIntent();
429 if (intent.getData() != null) {
430 // Get the intent data and convert it to a string.
431 final Uri intentUriData = intent.getData();
432 formattedUrlString = intentUriData.toString();
435 // If formattedUrlString is null assign the homepage to it.
436 if (formattedUrlString == null) {
437 formattedUrlString = homepage;
440 // Load the initial website.
441 mainWebView.loadUrl(formattedUrlString, customHeaders);
443 // If the favorite icon is null, load the default.
444 if (favoriteIcon == null) {
445 // We have to use `ContextCompat` until API >= 21.
446 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
447 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
448 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
451 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
452 adView = findViewById(R.id.adView);
453 BannerAd.requestAd(adView);
458 protected void onNewIntent(Intent intent) {
459 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
462 if (intent.getData() != null) {
463 // Get the intent data and convert it to a string.
464 final Uri intentUriData = intent.getData();
465 formattedUrlString = intentUriData.toString();
468 // Close the navigation drawer if it is open.
469 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
470 drawerLayout.closeDrawer(GravityCompat.START);
474 mainWebView.loadUrl(formattedUrlString, customHeaders);
476 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
477 mainWebView.requestFocus();
481 public boolean onCreateOptionsMenu(Menu menu) {
482 // Inflate the menu; this adds items to the action bar if it is present.
483 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
485 // Set mainMenu so it can be used by onOptionsItemSelected.
488 // Initialize privacyIcon
489 privacyIcon = menu.findItem(R.id.toggleJavaScript);
491 // Get MenuItems for checkable menu items.
492 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
493 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
494 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
495 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
497 // Set the initial status of the privacy icon.
500 // Set the initial status of the menu item checkboxes.
501 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
502 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
503 toggleDomStorage.setChecked(domStorageEnabled);
504 toggleSaveFormData.setChecked(saveFormDataEnabled);
510 public boolean onPrepareOptionsMenu(Menu menu) {
511 // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
512 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
513 if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
514 toggleThirdPartyCookies.setEnabled(true);
516 toggleThirdPartyCookies.setEnabled(false);
519 // Enable DOM Storage if JavaScript is enabled.
520 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
521 toggleDomStorage.setEnabled(javaScriptEnabled);
523 // Enable Clear Cookies if there are any.
524 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
525 clearCookies.setEnabled(cookieManager.hasCookies());
527 // Enable Clear Form Data is there is any.
528 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
529 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
530 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
532 // Run all the other default commands.
533 super.onPrepareOptionsMenu(menu);
535 // `return true` displays the menu.
540 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
541 @SuppressLint("SetJavaScriptEnabled")
542 // removeAllCookies is deprecated, but it is required for API < 21.
543 @SuppressWarnings("deprecation")
544 public boolean onOptionsItemSelected(MenuItem menuItem) {
545 int menuItemId = menuItem.getItemId();
547 // Set the commands that relate to the menu entries.
548 switch (menuItemId) {
549 case R.id.toggleJavaScript:
550 // Switch the status of javaScriptEnabled.
551 javaScriptEnabled = !javaScriptEnabled;
553 // Apply the new JavaScript status.
554 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
556 // Update the privacy icon.
559 // Display a Snackbar.
560 if (javaScriptEnabled) {
561 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
563 if (firstPartyCookiesEnabled) {
564 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
566 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
570 // Reload the WebView.
571 mainWebView.reload();
574 case R.id.toggleFirstPartyCookies:
575 // Switch the status of firstPartyCookiesEnabled.
576 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
578 // Update the menu checkbox.
579 menuItem.setChecked(firstPartyCookiesEnabled);
581 // Apply the new cookie status.
582 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
584 // Update the privacy icon.
587 // Reload the WebView.
588 mainWebView.reload();
591 case R.id.toggleThirdPartyCookies:
592 if (Build.VERSION.SDK_INT >= 21) {
593 // Switch the status of thirdPartyCookiesEnabled.
594 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
596 // Update the menu checkbox.
597 menuItem.setChecked(thirdPartyCookiesEnabled);
599 // Apply the new cookie status.
600 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
602 // Reload the WebView.
603 mainWebView.reload();
604 } // Else do nothing because SDK < 21.
607 case R.id.toggleDomStorage:
608 // Switch the status of domStorageEnabled.
609 domStorageEnabled = !domStorageEnabled;
611 // Update the menu checkbox.
612 menuItem.setChecked(domStorageEnabled);
614 // Apply the new DOM Storage status.
615 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
617 // Reload the WebView.
618 mainWebView.reload();
621 case R.id.toggleSaveFormData:
622 // Switch the status of saveFormDataEnabled.
623 saveFormDataEnabled = !saveFormDataEnabled;
625 // Update the menu checkbox.
626 menuItem.setChecked(saveFormDataEnabled);
628 // Apply the new form data status.
629 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
631 // Reload the WebView.
632 mainWebView.reload();
635 case R.id.clearCookies:
636 if (Build.VERSION.SDK_INT < 21) {
637 cookieManager.removeAllCookie();
639 cookieManager.removeAllCookies(null);
641 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
644 case R.id.clearDomStorage:
645 WebStorage webStorage = WebStorage.getInstance();
646 webStorage.deleteAllData();
647 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
650 case R.id.clearFormData:
651 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
652 mainWebViewDatabase.clearFormData();
653 mainWebView.reload();
657 Intent shareIntent = new Intent();
658 shareIntent.setAction(Intent.ACTION_SEND);
659 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
660 shareIntent.setType("text/plain");
661 startActivity(Intent.createChooser(shareIntent, "Share URL"));
664 case R.id.addToHomescreen:
665 // Show the CreateHomeScreenShortcut AlertDialog and name this instance "@string/create_shortcut".
666 DialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
667 createHomeScreenShortcutDialogFragment.show(getFragmentManager(), getResources().getString(R.string.create_shortcut));
669 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
673 mainWebView.reload();
677 // Don't consume the event.
678 return super.onOptionsItemSelected(menuItem);
683 // removeAllCookies is deprecated, but it is required for API < 21.
684 @SuppressWarnings("deprecation")
685 public boolean onNavigationItemSelected(MenuItem menuItem) {
686 int menuItemId = menuItem.getItemId();
688 switch (menuItemId) {
690 mainWebView.loadUrl(homepage, customHeaders);
694 if (mainWebView.canGoBack()) {
695 mainWebView.goBack();
700 if (mainWebView.canGoForward()) {
701 mainWebView.goForward();
706 // Launch BookmarksActivity.
707 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
708 startActivity(bookmarksIntent);
712 // Launch the system Download Manager.
713 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
715 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
716 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
718 startActivity(downloadManagerIntent);
722 // Launch `SettingsActivity`.
723 Intent settingsIntent = new Intent(this, SettingsActivity.class);
724 startActivity(settingsIntent);
728 // Launch `GuideActivity`.
729 Intent guideIntent = new Intent(this, GuideActivity.class);
730 startActivity(guideIntent);
734 // Launch `AboutActivity`.
735 Intent aboutIntent = new Intent(this, AboutActivity.class);
736 startActivity(aboutIntent);
739 case R.id.clearAndExit:
740 // Clear cookies. The commands changed slightly in API 21.
741 if (Build.VERSION.SDK_INT >= 21) {
742 cookieManager.removeAllCookies(null);
744 cookieManager.removeAllCookie();
747 // Clear DOM storage.
748 WebStorage domStorage = WebStorage.getInstance();
749 domStorage.deleteAllData();
752 WebViewDatabase formData = WebViewDatabase.getInstance(this);
753 formData.clearFormData();
755 // Clear cache. The argument of "true" includes disk files.
756 mainWebView.clearCache(true);
758 // Clear the back/forward history.
759 mainWebView.clearHistory();
761 formattedUrlString = null;
763 // Destroy the internal state of the webview.
764 mainWebView.destroy();
766 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
767 if (Build.VERSION.SDK_INT >= 21) {
768 finishAndRemoveTask();
778 // Close the navigation drawer.
779 drawerLayout.closeDrawer(GravityCompat.START);
784 public void onPostCreate(Bundle savedInstanceState) {
785 super.onPostCreate(savedInstanceState);
787 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
788 drawerToggle.syncState();
792 public void onConfigurationChanged(Configuration newConfig) {
793 super.onConfigurationChanged(newConfig);
795 // Reload the ad if this is the free flavor.
796 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
798 // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
799 adView = findViewById(R.id.adView);
803 public void onCancelCreateHomeScreenShortcut(DialogFragment dialogFragment) {
804 // Do nothing because the user selected "Cancel".
808 public void onCreateHomeScreenShortcut(DialogFragment dialogFragment) {
809 // Get shortcutNameEditText from the alert dialog.
810 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
812 // Create the bookmark shortcut based on formattedUrlString.
813 Intent bookmarkShortcut = new Intent();
814 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
815 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
817 // Place the bookmark shortcut on the home screen.
818 Intent placeBookmarkShortcut = new Intent();
819 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
820 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
821 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
822 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
823 sendBroadcast(placeBookmarkShortcut);
826 // Override onBackPressed to handle the navigation drawer and mainWebView.
828 public void onBackPressed() {
829 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
831 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
832 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
833 drawerLayout.closeDrawer(GravityCompat.START);
835 // Load the previous URL if available.
836 assert mainWebView != null; //This assert removes the incorrect warning in Android Studio on the following line that mainWebView might be null.
837 if (mainWebView.canGoBack()) {
838 mainWebView.goBack();
840 // Pass onBackPressed to the system.
841 super.onBackPressed();
847 public void onPause() {
848 // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
849 BannerAd.pauseAd(adView);
855 public void onResume() {
858 // We need to resume the adView for the free flavor.
859 BannerAd.resumeAd(adView);
862 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
863 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
864 String unformattedUrlString = urlTextBox.getText().toString().trim();
866 URL unformattedUrl = null;
867 Uri.Builder formattedUri = new Uri.Builder();
869 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
870 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
871 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
872 if (!unformattedUrlString.startsWith("http")) {
873 unformattedUrlString = "http://" + unformattedUrlString;
876 // 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.
878 unformattedUrl = new URL(unformattedUrlString);
879 } catch (MalformedURLException e) {
883 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
884 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
885 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
886 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
887 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
888 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
890 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
891 formattedUrlString = formattedUri.build().toString();
893 // Sanitize the search input and convert it to a DuckDuckGo search.
894 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
896 // Use the correct search URL based on javaScriptEnabled.
897 if (javaScriptEnabled) {
898 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
899 } else { // JavaScript is disabled.
900 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
904 mainWebView.loadUrl(formattedUrlString, customHeaders);
906 // Hides the keyboard so we can see the webpage.
907 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
908 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
911 private void updatePrivacyIcon() {
912 if (javaScriptEnabled) {
913 privacyIcon.setIcon(R.drawable.javascript_enabled);
915 if (firstPartyCookiesEnabled) {
916 privacyIcon.setIcon(R.drawable.warning);
918 privacyIcon.setIcon(R.drawable.privacy_mode);