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.net.Uri;
31 import android.os.Build;
32 import android.os.Bundle;
33 import android.preference.PreferenceManager;
34 import android.support.design.widget.NavigationView;
35 import android.support.design.widget.Snackbar;
36 import android.support.v4.view.GravityCompat;
37 import android.support.v4.widget.DrawerLayout;
38 import android.support.v4.widget.SwipeRefreshLayout;
39 import android.support.v7.app.ActionBar;
40 import android.support.v7.app.ActionBarDrawerToggle;
41 import android.support.v7.app.AppCompatActivity;
42 import android.support.v7.widget.Toolbar;
43 import android.util.Patterns;
44 import android.view.KeyEvent;
45 import android.view.Menu;
46 import android.view.MenuItem;
47 import android.view.View;
48 import android.view.inputmethod.InputMethodManager;
49 import android.webkit.CookieManager;
50 import android.webkit.DownloadListener;
51 import android.webkit.WebChromeClient;
52 import android.webkit.WebStorage;
53 import android.webkit.WebView;
54 import android.webkit.WebViewClient;
55 import android.webkit.WebViewDatabase;
56 import android.widget.EditText;
57 import android.widget.FrameLayout;
58 import android.widget.ImageView;
59 import android.widget.ProgressBar;
61 import java.io.UnsupportedEncodingException;
62 import java.net.MalformedURLException;
64 import java.net.URLEncoder;
66 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
67 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
68 // favoriteIcon is public static so it can be accessed from CreateHomeScreenShortcut and BookmarksActivity.
69 // It is also used in onCreate() and onCreateHomeScreenShortcutCreate().
70 public static Bitmap favoriteIcon;
72 // mainWebView is public static so it can be accessed from SettingsFragment.
73 // It is also used in onCreate(), onOptionsItemSelected(), onNavigationItemSelected(), and loadUrlFromTextBox().
74 public static WebView mainWebView;
76 // formattedUrlString is public static so it can be accessed from BookmarksActivity.
77 // It is also used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
78 public static String formattedUrlString;
80 // mainMenu is public static so it can be accessed from SettingsFragment. It is also used in onCreateOptionsMenu() and onOptionsItemSelected().
81 public static Menu mainMenu;
83 // cookieManager is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onOptionsItemSelected(), and onNavigationItemSelected().
84 public static CookieManager cookieManager;
86 // javaScriptEnabled is public static so it can be accessed from SettingsFragment.
87 // It is also used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
88 public static boolean javaScriptEnabled;
90 // firstPartyCookiesEnabled is public static so it can be accessed from SettingsFragment.
91 // It is also used in onCreate(), onCreateOptionsMenu(), onPrepareOptionsMenu(), and onOptionsItemSelected().
92 public static boolean firstPartyCookiesEnabled;
94 // thirdPartyCookiesEnabled is used in onCreate(), onCreateOptionsMenu(), onPrepareOptionsMenu(), and onOptionsItemSelected().
95 public static boolean thirdPartyCookiesEnabled;
97 // domStorageEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
98 public static boolean domStorageEnabled;
100 // saveFormDataEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
101 public static boolean saveFormDataEnabled;
103 // javaScriptDisabledSearchURL is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and loadURLFromTextBox().
104 public static String javaScriptDisabledSearchURL;
106 // javaScriptEnabledSearchURL is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and loadURLFromTextBox().
107 public static String javaScriptEnabledSearchURL;
109 // homepage is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and onOptionsItemSelected().
110 public static String homepage;
112 // swipeToRefresh is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
113 public static SwipeRefreshLayout swipeToRefresh;
115 // swipeToRefreshEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
116 public static boolean swipeToRefreshEnabled;
120 // drawerToggle is used in onCreate(), onPostCreate(), onConfigurationChanged(), onNewIntent(), and onNavigationItemSelected().
121 private ActionBarDrawerToggle drawerToggle;
123 // drawerLayout is used in onCreate(), onNewIntent(), and onBackPressed().
124 private DrawerLayout drawerLayout;
126 // privacyIcon is used in onCreateOptionsMenu() and updatePrivacyIcon().
127 private MenuItem privacyIcon;
129 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
130 private EditText urlTextBox;
132 // adView is used in onCreate() and onConfigurationChanged().
136 // 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.
137 @SuppressLint("SetJavaScriptEnabled")
138 protected void onCreate(Bundle savedInstanceState) {
139 super.onCreate(savedInstanceState);
140 setContentView(R.layout.main_coordinatorlayout);
142 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
143 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
144 setSupportActionBar(supportAppBar);
145 final ActionBar appBar = getSupportActionBar();
147 // This is needed to get rid of the Android Studio warning that appBar might be null.
148 assert appBar != null;
150 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
151 appBar.setCustomView(R.layout.url_bar);
152 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
154 // Set the "go" button on the keyboard to load the URL in urlTextBox.
155 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
156 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
157 public boolean onKey(View v, int keyCode, KeyEvent event) {
158 // If the event is a key-down event on the "enter" button, load the URL.
159 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
160 // Load the URL into the mainWebView and consume the event.
162 loadUrlFromTextBox();
163 } catch (UnsupportedEncodingException e) {
166 // If the enter key was pressed, consume the event.
169 // If any other key was pressed, do not consume the event.
175 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
177 // Implement swipe to refresh
178 swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
179 assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null.
180 swipeToRefresh.setColorSchemeResources(R.color.blue);
181 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
183 public void onRefresh() {
184 mainWebView.reload();
188 mainWebView = (WebView) findViewById(R.id.mainWebView);
190 // Create the navigation drawer.
191 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
192 // The DrawerTitle identifies the drawer in accessibility mode.
193 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
195 // Listen for touches on the navigation menu.
196 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
197 assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null.
198 navigationView.setNavigationItemSelectedListener(this);
200 // drawerToggle creates the hamburger icon at the start of the AppBar.
201 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
203 mainWebView.setWebViewClient(new WebViewClient() {
204 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
206 public boolean shouldOverrideUrlLoading(WebView view, String url) {
207 mainWebView.loadUrl(url);
211 // Update the URL in urlTextBox when the page starts to load.
213 public void onPageStarted(WebView view, String url, Bitmap favicon) {
214 urlTextBox.setText(url);
217 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
219 public void onPageFinished(WebView view, String url) {
220 formattedUrlString = url;
222 // Only update urlTextBox if the user is not typing in it.
223 if (!urlTextBox.hasFocus()) {
224 urlTextBox.setText(formattedUrlString);
229 mainWebView.setWebChromeClient(new WebChromeClient() {
230 // Update the progress bar when a page is loading.
232 public void onProgressChanged(WebView view, int progress) {
233 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
234 progressBar.setProgress(progress);
235 if (progress < 100) {
236 progressBar.setVisibility(View.VISIBLE);
238 progressBar.setVisibility(View.GONE);
240 //Stop the SwipeToRefresh indicator if it is running
241 swipeToRefresh.setRefreshing(false);
245 // Set the favorite icon when it changes.
247 public void onReceivedIcon(WebView view, Bitmap icon) {
248 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
251 // Place the favorite icon in the appBar.
252 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
253 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
256 // Enter full screen video
258 public void onShowCustomView(View view, CustomViewCallback callback) {
261 // Show the fullScreenVideoFrameLayout.
262 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
263 fullScreenVideoFrameLayout.addView(view);
264 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
266 // Hide the mainWebView.
267 mainWebView.setVisibility(View.GONE);
269 // Hide the ad if this is the free flavor.
270 BannerAd.hideAd(adView);
272 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
273 * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
274 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
276 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
279 // Exit full screen video
280 public void onHideCustomView() {
283 // Show the mainWebView.
284 mainWebView.setVisibility(View.VISIBLE);
286 // Show the ad if this is the free flavor.
287 BannerAd.showAd(adView);
289 // Hide the fullScreenVideoFrameLayout.
290 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
291 fullScreenVideoFrameLayout.removeAllViews();
292 fullScreenVideoFrameLayout.setVisibility(View.GONE);
296 // Allow the downloading of files.
297 mainWebView.setDownloadListener(new DownloadListener() {
298 // Launch the Android download manager when a link leads to a download.
300 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
301 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
302 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
304 // Add the URL as the description for the download.
305 requestUri.setDescription(url);
307 // Show the download notification after the download is completed.
308 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
310 // Initiate the download and display a Snackbar.
311 downloadManager.enqueue(requestUri);
312 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
316 // Allow pinch to zoom.
317 mainWebView.getSettings().setBuiltInZoomControls(true);
319 // Hide zoom controls.
320 mainWebView.getSettings().setDisplayZoomControls(false);
323 // Initialize the default preference values the first time the program is run.
324 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
326 // Get the shared preference values.
327 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
329 // Set JavaScript initial status. The default value is false.
330 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
331 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
333 // Initialize cookieManager.
334 cookieManager = CookieManager.getInstance();
336 // Set cookies initial status. The default value is false.
337 firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false);
338 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
340 // Set third-party cookies initial status if API >= 21. The default value is false.
341 if (Build.VERSION.SDK_INT >= 21) {
342 thirdPartyCookiesEnabled = savedPreferences.getBoolean("third_party_cookies_enabled", false);
343 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
346 // Set DOM storage initial status. The default value is false.
347 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
348 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
350 // Set the saved form data initial status. The default is false.
351 saveFormDataEnabled = savedPreferences.getBoolean("save_form_data_enabled", false);
352 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
354 // Set the user agent initial status.
355 String userAgentString = savedPreferences.getString("user_agent", "Default user agent");
356 switch (userAgentString) {
357 case "Default user agent":
361 case "Custom user agent":
362 // Set the custom user agent on mainWebView, The default is "PrivacyBrowser/1.0".
363 mainWebView.getSettings().setUserAgentString(savedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0"));
367 // Set the selected user agent on mainWebView. The default is "PrivacyBrowser/1.0".
368 mainWebView.getSettings().setUserAgentString(savedPreferences.getString("user_agent", "PrivacyBrowser/1.0"));
372 // Set the initial string for JavaScript disabled search.
373 if (savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=").equals("Custom URL")) {
374 // Get the custom URL string. The default is "".
375 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search_custom_url", "");
377 // Use the string from javascript_disabled_search.
378 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
381 // Set the initial string for JavaScript enabled search.
382 if (savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=").equals("Custom URL")) {
383 // Get the custom URL string. The default is "".
384 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search_custom_url", "");
386 // Use the string from javascript_enabled_search.
387 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
391 // Set homepage initial status. The default value is "https://www.duckduckgo.com".
392 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
394 // Set swipe to refresh initial status. The default is true.
395 swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
396 swipeToRefresh.setEnabled(swipeToRefreshEnabled);
399 // Get the intent information that started the app.
400 final Intent intent = getIntent();
402 if (intent.getData() != null) {
403 // Get the intent data and convert it to a string.
404 final Uri intentUriData = intent.getData();
405 formattedUrlString = intentUriData.toString();
408 // If formattedUrlString is null assign the homepage to it.
409 if (formattedUrlString == null) {
410 formattedUrlString = homepage;
413 // Load the initial website.
414 mainWebView.loadUrl(formattedUrlString);
416 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
417 adView = findViewById(R.id.adView);
418 BannerAd.requestAd(adView);
423 protected void onNewIntent(Intent intent) {
424 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
427 if (intent.getData() != null) {
428 // Get the intent data and convert it to a string.
429 final Uri intentUriData = intent.getData();
430 formattedUrlString = intentUriData.toString();
433 // Close the navigation drawer if it is open.
434 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
435 drawerLayout.closeDrawer(GravityCompat.START);
439 mainWebView.loadUrl(formattedUrlString);
441 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
442 mainWebView.requestFocus();
446 public boolean onCreateOptionsMenu(Menu menu) {
447 // Inflate the menu; this adds items to the action bar if it is present.
448 getMenuInflater().inflate(R.menu.menu_options, menu);
450 // Set mainMenu so it can be used by onOptionsItemSelected.
453 // Initialize privacyIcon
454 privacyIcon = menu.findItem(R.id.toggleJavaScript);
456 // Get MenuItems for checkable menu items.
457 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
458 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
459 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
460 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
462 // Set the initial status of the privacy icon.
465 // Set the initial status of the menu item checkboxes.
466 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
467 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
468 toggleDomStorage.setChecked(domStorageEnabled);
469 toggleSaveFormData.setChecked(saveFormDataEnabled);
475 public boolean onPrepareOptionsMenu(Menu menu) {
476 // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
477 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
478 if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
479 toggleThirdPartyCookies.setEnabled(true);
481 toggleThirdPartyCookies.setEnabled(false);
484 // Enable DOM Storage if JavaScript is enabled.
485 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
486 toggleDomStorage.setEnabled(javaScriptEnabled);
488 // Enable Clear Cookies if there are any.
489 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
490 clearCookies.setEnabled(cookieManager.hasCookies());
492 // Enable Clear Form Data is there is any.
493 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
494 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
495 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
497 // Run all the other default commands.
498 super.onPrepareOptionsMenu(menu);
500 // return true displays the menu.
505 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
506 @SuppressLint("SetJavaScriptEnabled")
507 // removeAllCookies is deprecated, but it is required for API < 21.
508 @SuppressWarnings("deprecation")
509 public boolean onOptionsItemSelected(MenuItem menuItem) {
510 int menuItemId = menuItem.getItemId();
512 // Set the commands that relate to the menu entries.
513 switch (menuItemId) {
514 case R.id.toggleJavaScript:
515 // Switch the status of javaScriptEnabled.
516 javaScriptEnabled = !javaScriptEnabled;
518 // Apply the new JavaScript status.
519 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
521 // Update the privacy icon.
524 // Display a Snackbar.
525 if (javaScriptEnabled) {
526 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
528 if (firstPartyCookiesEnabled) {
529 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
531 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
535 // Reload the WebView.
536 mainWebView.reload();
539 case R.id.toggleFirstPartyCookies:
540 // Switch the status of firstPartyCookiesEnabled.
541 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
543 // Update the menu checkbox.
544 menuItem.setChecked(firstPartyCookiesEnabled);
546 // Apply the new cookie status.
547 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
549 // Update the privacy icon.
552 // Reload the WebView.
553 mainWebView.reload();
556 case R.id.toggleThirdPartyCookies:
557 if (Build.VERSION.SDK_INT >= 21) {
558 // Switch the status of thirdPartyCookiesEnabled.
559 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
561 // Update the menu checkbox.
562 menuItem.setChecked(thirdPartyCookiesEnabled);
564 // Apply the new cookie status.
565 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
567 // Reload the WebView.
568 mainWebView.reload();
569 } // Else do nothing because SDK < 21.
572 case R.id.toggleDomStorage:
573 // Switch the status of domStorageEnabled.
574 domStorageEnabled = !domStorageEnabled;
576 // Update the menu checkbox.
577 menuItem.setChecked(domStorageEnabled);
579 // Apply the new DOM Storage status.
580 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
582 // Reload the WebView.
583 mainWebView.reload();
586 case R.id.toggleSaveFormData:
587 // Switch the status of saveFormDataEnabled.
588 saveFormDataEnabled = !saveFormDataEnabled;
590 // Update the menu checkbox.
591 menuItem.setChecked(saveFormDataEnabled);
593 // Apply the new form data status.
594 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
596 // Reload the WebView.
597 mainWebView.reload();
600 case R.id.clearCookies:
601 if (Build.VERSION.SDK_INT < 21) {
602 cookieManager.removeAllCookie();
604 cookieManager.removeAllCookies(null);
606 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
609 case R.id.clearDomStorage:
610 WebStorage webStorage = WebStorage.getInstance();
611 webStorage.deleteAllData();
612 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
615 case R.id.clearFormData:
616 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
617 mainWebViewDatabase.clearFormData();
618 mainWebView.reload();
622 Intent shareIntent = new Intent();
623 shareIntent.setAction(Intent.ACTION_SEND);
624 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
625 shareIntent.setType("text/plain");
626 startActivity(Intent.createChooser(shareIntent, "Share URL"));
629 case R.id.addToHomescreen:
630 // Show the CreateHomeScreenShortcut AlertDialog and name this instance "@string/create_shortcut".
631 DialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
632 createHomeScreenShortcutDialogFragment.show(getFragmentManager(), "@string/create_shortcut");
634 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
638 mainWebView.reload();
642 // Don't consume the event.
643 return super.onOptionsItemSelected(menuItem);
648 // removeAllCookies is deprecated, but it is required for API < 21.
649 @SuppressWarnings("deprecation")
650 public boolean onNavigationItemSelected(MenuItem menuItem) {
651 int menuItemId = menuItem.getItemId();
653 switch (menuItemId) {
655 mainWebView.loadUrl(homepage);
659 if (mainWebView.canGoBack()) {
660 mainWebView.goBack();
665 if (mainWebView.canGoForward()) {
666 mainWebView.goForward();
671 // Launch BookmarksActivity.
672 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
673 startActivity(bookmarksIntent);
677 // Launch the system Download Manager.
678 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
680 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
681 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
683 startActivity(downloadManagerIntent);
687 // Launch SettingsActivity.
688 Intent settingsIntent = new Intent(this, SettingsActivity.class);
689 startActivity(settingsIntent);
693 // Launch GuideActivity.
694 Intent guideIntent = new Intent(this, GuideActivity.class);
695 startActivity(guideIntent);
699 // Launch AboutActivity.
700 Intent aboutIntent = new Intent(this, AboutActivity.class);
701 startActivity(aboutIntent);
704 case R.id.clearAndExit:
705 // Clear cookies. The commands changed slightly in API 21.
706 if (Build.VERSION.SDK_INT >= 21) {
707 cookieManager.removeAllCookies(null);
709 cookieManager.removeAllCookie();
712 // Clear DOM storage.
713 WebStorage domStorage = WebStorage.getInstance();
714 domStorage.deleteAllData();
717 WebViewDatabase formData = WebViewDatabase.getInstance(this);
718 formData.clearFormData();
720 // Clear cache. The argument of "true" includes disk files.
721 mainWebView.clearCache(true);
723 // Clear the back/forward history.
724 mainWebView.clearHistory();
726 // Destroy the internal state of the webview.
727 mainWebView.destroy();
729 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
730 if (Build.VERSION.SDK_INT >= 21) {
731 finishAndRemoveTask();
741 // Close the navigation drawer.
742 drawerLayout.closeDrawer(GravityCompat.START);
747 public void onPostCreate(Bundle savedInstanceState) {
748 super.onPostCreate(savedInstanceState);
750 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
751 drawerToggle.syncState();
755 public void onConfigurationChanged(Configuration newConfig) {
756 super.onConfigurationChanged(newConfig);
758 // Reload the ad if this is the free flavor.
759 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
761 // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
762 adView = findViewById(R.id.adView);
766 public void onCreateHomeScreenShortcutCancel(DialogFragment dialogFragment) {
767 // Do nothing because the user selected "Cancel".
771 public void onCreateHomeScreenShortcutCreate(DialogFragment dialogFragment) {
772 // Get shortcutNameEditText from the alert dialog.
773 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
775 // Create the bookmark shortcut based on formattedUrlString.
776 Intent bookmarkShortcut = new Intent();
777 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
778 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
780 // Place the bookmark shortcut on the home screen.
781 Intent placeBookmarkShortcut = new Intent();
782 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
783 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
784 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
785 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
786 sendBroadcast(placeBookmarkShortcut);
789 // Override onBackPressed to handle the navigation drawer and mainWebView.
791 public void onBackPressed() {
792 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
794 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
795 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
796 drawerLayout.closeDrawer(GravityCompat.START);
798 // Load the previous URL if available.
799 assert mainWebView != null; //This assert removes the incorrect warning in Android Studio on the following line that mainWebView might be null.
800 if (mainWebView.canGoBack()) {
801 mainWebView.goBack();
803 // Pass onBackPressed to the system.
804 super.onBackPressed();
810 public void onPause() {
811 // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
812 BannerAd.pauseAd(adView);
818 public void onResume() {
821 // We need to resume the adView for the free flavor.
822 BannerAd.resumeAd(adView);
825 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
826 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
827 String unformattedUrlString = urlTextBox.getText().toString().trim();
829 URL unformattedUrl = null;
830 Uri.Builder formattedUri = new Uri.Builder();
832 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
833 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
834 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
835 if (!unformattedUrlString.startsWith("http")) {
836 unformattedUrlString = "http://" + unformattedUrlString;
839 // 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.
841 unformattedUrl = new URL(unformattedUrlString);
842 } catch (MalformedURLException e) {
846 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
847 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
848 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
849 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
850 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
851 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
853 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
854 formattedUrlString = formattedUri.build().toString();
856 // Sanitize the search input and convert it to a DuckDuckGo search.
857 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
859 // Use the correct search URL based on javaScriptEnabled.
860 if (javaScriptEnabled) {
861 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
862 } else { // JavaScript is disabled.
863 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
867 mainWebView.loadUrl(formattedUrlString);
869 // Hides the keyboard so we can see the webpage.
870 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
871 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
874 private void updatePrivacyIcon() {
875 if (javaScriptEnabled) {
876 privacyIcon.setIcon(R.drawable.javascript_enabled);
878 if (firstPartyCookiesEnabled) {
879 privacyIcon.setIcon(R.drawable.warning);
881 privacyIcon.setIcon(R.drawable.privacy_mode);