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.DownloadManager;
25 import android.content.Intent;
26 import android.content.SharedPreferences;
27 import android.content.res.Configuration;
28 import android.graphics.Bitmap;
29 import android.net.Uri;
30 import android.os.Build;
31 import android.os.Bundle;
32 import android.preference.PreferenceManager;
33 import android.support.design.widget.NavigationView;
34 import android.support.design.widget.Snackbar;
35 import android.support.v4.app.DialogFragment;
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.app.AppCompatDialogFragment;
43 import android.support.v7.widget.Toolbar;
44 import android.util.Patterns;
45 import android.view.KeyEvent;
46 import android.view.Menu;
47 import android.view.MenuItem;
48 import android.view.View;
49 import android.view.inputmethod.InputMethodManager;
50 import android.webkit.CookieManager;
51 import android.webkit.DownloadListener;
52 import android.webkit.WebChromeClient;
53 import android.webkit.WebStorage;
54 import android.webkit.WebView;
55 import android.webkit.WebViewClient;
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.
69 public static Bitmap favoriteIcon;
70 // mainWebView is public static so it can be accessed from AboutDialog and SettingsFragment. It is also used in onCreate(), onOptionsItemSelected(), onNavigationItemSelected(), and loadUrlFromTextBox().
71 public static WebView mainWebView;
73 // mainMenu is public static so it can be accessed from SettingsFragment. It is also used in onCreateOptionsMenu() and onOptionsItemSelected().
74 public static Menu mainMenu;
75 // cookieManager is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onOptionsItemSelected(), and onNavigationItemSelected().
76 public static CookieManager cookieManager;
77 // javaScriptEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
78 public static boolean javaScriptEnabled;
79 // firstPartyCookiesEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onCreateOptionsMenu(), onPrepareOptionsMenu(), and onOptionsItemSelected().
80 public static boolean firstPartyCookiesEnabled;
81 // thirdPartyCookiesEnabled is uesd in onCreate(), onCreateOptionsMenu(), onPrepareOptionsMenu(), and onOptionsItemSelected().
82 public static boolean thirdPartyCookiesEnabled;
83 // domStorageEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
84 public static boolean domStorageEnabled;
85 // homepage is public static so it can be accessed from SettingsFragment. It is also used in onCreate() and onOptionsItemSelected().
86 public static String homepage;
87 // swipeToRefresh is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
88 public static SwipeRefreshLayout swipeToRefresh;
89 // swipeToRefreshEnabled is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
90 public static boolean swipeToRefreshEnabled;
92 // drawerToggle is used in onCreate(), onPostCreate(), onConfigurationChanged(), onNewIntent(), and onNavigationItemSelected().
93 private ActionBarDrawerToggle drawerToggle;
94 // drawerLayout is used in onCreate(), onNewIntent(), and onBackPressed().
95 private DrawerLayout drawerLayout;
96 // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
97 private String formattedUrlString;
99 // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
100 private EditText urlTextBox;
103 // 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.
104 @SuppressLint("SetJavaScriptEnabled")
105 protected void onCreate(Bundle savedInstanceState) {
106 super.onCreate(savedInstanceState);
107 setContentView(R.layout.coordinator_layout);
109 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
110 Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
111 setSupportActionBar(supportAppBar);
113 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
115 // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
116 final ActionBar appBar = getSupportActionBar();
118 // Setup AdView for the free flavor.
119 final View adView = findViewById(R.id.adView);
121 // Implement swipe to refresh
122 swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
123 swipeToRefresh.setColorSchemeResources(R.color.blue);
124 swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
126 public void onRefresh() {
127 mainWebView.reload();
131 mainWebView = (WebView) findViewById(R.id.mainWebView);
133 if (appBar != null) {
134 // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
135 appBar.setCustomView(R.layout.url_bar);
136 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
138 // Set the "go" button on the keyboard to load the URL in urlTextBox.
139 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
140 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
141 public boolean onKey(View v, int keyCode, KeyEvent event) {
142 // If the event is a key-down event on the "enter" button, load the URL.
143 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
144 // Load the URL into the mainWebView and consume the event.
146 loadUrlFromTextBox();
147 } catch (UnsupportedEncodingException e) {
150 // If the enter key was pressed, consume the event.
153 // If any other key was pressed, do not consume the event.
160 // Create the navigation drawer.
161 drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
162 // The DrawerTitle identifies the drawer in accessibility mode.
163 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
165 // Listen for touches on the navigation menu.
166 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
167 navigationView.setNavigationItemSelectedListener(this);
169 // drawerToggle creates the hamburger icon at the start of the AppBar.
170 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
172 mainWebView.setWebViewClient(new WebViewClient() {
173 // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
175 public boolean shouldOverrideUrlLoading(WebView view, String url) {
176 mainWebView.loadUrl(url);
180 // Update the URL in urlTextBox when the page starts to load.
182 public void onPageStarted(WebView view, String url, Bitmap favicon) {
183 urlTextBox.setText(url);
186 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
188 public void onPageFinished(WebView view, String url) {
189 formattedUrlString = url;
191 // Only update urlTextBox if the user is not typing in it.
192 if (!urlTextBox.hasFocus()) {
193 urlTextBox.setText(formattedUrlString);
198 mainWebView.setWebChromeClient(new WebChromeClient() {
199 // Update the progress bar when a page is loading.
201 public void onProgressChanged(WebView view, int progress) {
202 // Make sure that appBar is not null.
203 if (appBar != null) {
204 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
205 progressBar.setProgress(progress);
206 if (progress < 100) {
207 progressBar.setVisibility(View.VISIBLE);
209 progressBar.setVisibility(View.GONE);
211 //Stop the SwipeToRefresh indicator if it is running
212 swipeToRefresh.setRefreshing(false);
217 // Set the favorite icon when it changes.
219 public void onReceivedIcon(WebView view, Bitmap icon) {
220 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
223 // Place the favorite icon in the appBar if it is not null.
224 if (appBar != null) {
225 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
226 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
230 // Enter full screen video
232 public void onShowCustomView(View view, CustomViewCallback callback) {
233 if (appBar != null) {
237 // Show the fullScreenVideoFrameLayout.
238 fullScreenVideoFrameLayout.addView(view);
239 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
241 // Hide the mainWebView.
242 mainWebView.setVisibility(View.GONE);
244 // Hide the ad if this is the free flavor.
245 BannerAd.hideAd(adView);
247 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
248 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
249 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
252 // Set the one flag supported by API >= 14.
253 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
255 // Set the two flags that are supported by API >= 16.
256 if (Build.VERSION.SDK_INT >= 16) {
257 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
260 // Set all three flags that are supported by API >= 19.
261 if (Build.VERSION.SDK_INT >= 19) {
262 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
266 // Exit full screen video
267 public void onHideCustomView() {
268 if (appBar != null) {
272 // Show the mainWebView.
273 mainWebView.setVisibility(View.VISIBLE);
275 // Show the ad if this is the free flavor.
276 BannerAd.showAd(adView);
278 // Hide the fullScreenVideoFrameLayout.
279 fullScreenVideoFrameLayout.removeAllViews();
280 fullScreenVideoFrameLayout.setVisibility(View.GONE);
284 // Allow the downloading of files.
285 mainWebView.setDownloadListener(new DownloadListener() {
286 // Launch the Android download manager when a link leads to a download.
288 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
289 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
290 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
292 // Add the URL as the description for the download.
293 requestUri.setDescription(url);
295 // Show the download notification after the download is completed.
296 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
298 // Initiate the download and display a Snackbar.
299 downloadManager.enqueue(requestUri);
300 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
304 // Allow pinch to zoom.
305 mainWebView.getSettings().setBuiltInZoomControls(true);
307 // Hide zoom controls.
308 mainWebView.getSettings().setDisplayZoomControls(false);
311 // Initialize the default preference values the first time the program is run.
312 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
314 // Get the shared preference values.
315 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
317 // Set JavaScript initial status.
318 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
319 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
321 // Initialize cookieManager.
322 cookieManager = CookieManager.getInstance();
324 // Set cookies initial status.
325 firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false);
326 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
328 // Set third-party cookies initial status if API >= 21.
329 if (Build.VERSION.SDK_INT >= 21) {
330 thirdPartyCookiesEnabled = savedPreferences.getBoolean("third_party_cookies_enabled", false);
331 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
334 // Set DOM storage initial status.
335 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
336 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
338 // Set homepage initial status.
339 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
341 // Set swipe to refresh initial status. The default is true.
342 swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
343 swipeToRefresh.setEnabled(swipeToRefreshEnabled);
346 // Get the intent information that started the app.
347 final Intent intent = getIntent();
349 if (intent.getData() != null) {
350 // Get the intent data and convert it to a string.
351 final Uri intentUriData = intent.getData();
352 formattedUrlString = intentUriData.toString();
355 // If formattedUrlString is null assign the homepage to it.
356 if (formattedUrlString == null) {
357 formattedUrlString = homepage;
360 // Load the initial website.
361 mainWebView.loadUrl(formattedUrlString);
363 // Load the ad if this is the free flavor.
364 BannerAd.requestAd(adView);
368 protected void onNewIntent(Intent intent) {
369 // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
372 if (intent.getData() != null) {
373 // Get the intent data and convert it to a string.
374 final Uri intentUriData = intent.getData();
375 formattedUrlString = intentUriData.toString();
378 // Close the navigation drawer if it is open.
379 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
380 drawerLayout.closeDrawer(GravityCompat.START);
384 mainWebView.loadUrl(formattedUrlString);
386 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
387 mainWebView.requestFocus();
391 public boolean onCreateOptionsMenu(Menu menu) {
392 // Inflate the menu; this adds items to the action bar if it is present.
393 getMenuInflater().inflate(R.menu.menu_options, menu);
395 // Set mainMenu so it can be used by onOptionsItemSelected.
398 // Get MenuItems for checkable menu items.
399 MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
400 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
401 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
402 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
403 /* toggleSaveFormData does nothing until database storage is implemented.
404 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
407 // Set the initial icon for toggleJavaScript
408 if (javaScriptEnabled) {
409 toggleJavaScript.setIcon(R.drawable.javascript_enabled);
411 if (domStorageEnabled || firstPartyCookiesEnabled) {
412 toggleJavaScript.setIcon(R.drawable.warning);
414 toggleJavaScript.setIcon(R.drawable.privacy_mode);
418 // Set the initial status of the menu item checkboxes.
419 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
420 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
421 toggleDomStorage.setChecked(domStorageEnabled);
422 /* toggleSaveFormData does nothing until database storage is implemented.
423 toggleSaveFormData.setChecked(saveFormDataEnabled);
430 public boolean onPrepareOptionsMenu(Menu menu) {
431 // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
432 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
433 if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
434 toggleThirdPartyCookies.setEnabled(true);
436 toggleThirdPartyCookies.setEnabled(false);
439 // Enable Clear Cookies if there are any.
440 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
441 clearCookies.setEnabled(cookieManager.hasCookies());
443 // Run all the other default commands.
444 super.onPrepareOptionsMenu(menu);
446 // return true displays the menu.
451 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
452 @SuppressLint("SetJavaScriptEnabled")
453 // removeAllCookies is deprecated, but it is required for API < 21.
454 @SuppressWarnings("deprecation")
455 public boolean onOptionsItemSelected(MenuItem menuItem) {
456 int menuItemId = menuItem.getItemId();
458 // Some options need to update the drawable for toggleJavaScript.
459 MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
461 // Set the commands that relate to the menu entries.
462 switch (menuItemId) {
463 case R.id.toggleJavaScript:
464 if (javaScriptEnabled) {
465 javaScriptEnabled = false;
466 mainWebView.getSettings().setJavaScriptEnabled(false);
467 mainWebView.reload();
469 // Update the toggleJavaScript icon and display a snackbar.
470 if (domStorageEnabled || firstPartyCookiesEnabled) {
471 menuItem.setIcon(R.drawable.warning);
472 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
474 menuItem.setIcon(R.drawable.privacy_mode);
475 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
478 javaScriptEnabled = true;
479 menuItem.setIcon(R.drawable.javascript_enabled);
480 mainWebView.getSettings().setJavaScriptEnabled(true);
481 mainWebView.reload();
482 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
486 case R.id.toggleFirstPartyCookies:
487 if (firstPartyCookiesEnabled) {
488 firstPartyCookiesEnabled = false;
489 menuItem.setChecked(false);
490 cookieManager.setAcceptCookie(false);
491 mainWebView.reload();
493 // Update the toggleJavaScript icon if appropriate and display a snackbar.
494 if (!javaScriptEnabled) {
495 if (domStorageEnabled) {
496 toggleJavaScript.setIcon(R.drawable.warning);
497 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
499 toggleJavaScript.setIcon(R.drawable.privacy_mode);
500 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
503 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
506 firstPartyCookiesEnabled = true;
507 menuItem.setChecked(true);
508 cookieManager.setAcceptCookie(true);
509 mainWebView.reload();
511 // Update the toggleJavaScript icon if appropriate.
512 if (!javaScriptEnabled) {
513 toggleJavaScript.setIcon(R.drawable.warning);
514 } // Else do nothing because JavaScript is enabled.
516 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
520 case R.id.toggleThirdPartyCookies:
521 if (Build.VERSION.SDK_INT >= 21) {
522 if (thirdPartyCookiesEnabled) {
523 thirdPartyCookiesEnabled = false;
524 menuItem.setChecked(false);
525 cookieManager.setAcceptThirdPartyCookies(mainWebView, false);
526 mainWebView.reload();
528 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
530 thirdPartyCookiesEnabled = true;
531 menuItem.setChecked(true);
532 cookieManager.setAcceptThirdPartyCookies(mainWebView, true);
533 mainWebView.reload();
535 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
537 } // Else do nothing because SDK < 21.
540 case R.id.toggleDomStorage:
541 if (domStorageEnabled) {
542 domStorageEnabled = false;
543 menuItem.setChecked(false);
544 mainWebView.getSettings().setDomStorageEnabled(false);
545 mainWebView.reload();
547 // Update the toggleJavaScript icon if appropriate and display a snackbar.
548 if (!javaScriptEnabled) {
549 if (firstPartyCookiesEnabled) {
550 toggleJavaScript.setIcon(R.drawable.warning);
551 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
553 toggleJavaScript.setIcon(R.drawable.privacy_mode);
554 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
557 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
560 domStorageEnabled = true;
561 menuItem.setChecked(true);
562 mainWebView.getSettings().setDomStorageEnabled(true);
563 mainWebView.reload();
565 // Update the toggleJavaScript icon if appropriate.
566 if (!javaScriptEnabled) {
567 toggleJavaScript.setIcon(R.drawable.warning);
568 } // Else Do nothing because JavaScript is enabled.
570 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
574 case R.id.clearCookies:
575 if (Build.VERSION.SDK_INT < 21) {
576 cookieManager.removeAllCookie();
578 cookieManager.removeAllCookies(null);
580 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
583 case R.id.clearDomStorage:
584 WebStorage webStorage = WebStorage.getInstance();
585 webStorage.deleteAllData();
586 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
590 Intent shareIntent = new Intent();
591 shareIntent.setAction(Intent.ACTION_SEND);
592 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
593 shareIntent.setType("text/plain");
594 startActivity(Intent.createChooser(shareIntent, "Share URL"));
597 case R.id.addToHomescreen:
598 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
599 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
600 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
602 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
606 mainWebView.reload();
609 return super.onOptionsItemSelected(menuItem);
614 // removeAllCookies is deprecated, but it is required for API < 21.
615 @SuppressWarnings("deprecation")
616 public boolean onNavigationItemSelected(MenuItem menuItem) {
617 int menuItemId = menuItem.getItemId();
619 switch (menuItemId) {
621 mainWebView.loadUrl(homepage);
625 if (mainWebView.canGoBack()) {
626 mainWebView.goBack();
631 if (mainWebView.canGoForward()) {
632 mainWebView.goForward();
637 // Launch the system Download Manager.
638 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
640 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
641 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
643 startActivity(downloadManagerIntent);
647 // Launch PreferenceFragment.
648 Intent intent = new Intent(this, SettingsActivity.class);
649 startActivity(intent);
653 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
654 AppCompatDialogFragment aboutDialog = new AboutDialog();
655 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
658 case R.id.clearAndExit:
659 // Clear DOM storage.
660 WebStorage domStorage = WebStorage.getInstance();
661 domStorage.deleteAllData();
663 // Clear cookies. The commands changed slightly in API 21.
664 if (Build.VERSION.SDK_INT >= 21) {
665 cookieManager.removeAllCookies(null);
667 cookieManager.removeAllCookie();
670 // Destroy the internal state of the webview.
671 mainWebView.destroy();
673 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
674 if (Build.VERSION.SDK_INT >= 21) {
675 finishAndRemoveTask();
685 // Close the navigation drawer.
686 drawerLayout.closeDrawer(GravityCompat.START);
691 public void onPostCreate(Bundle savedInstanceState) {
692 super.onPostCreate(savedInstanceState);
694 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
695 drawerToggle.syncState();
699 public void onConfigurationChanged(Configuration newConfig) {
700 super.onConfigurationChanged(newConfig);
702 // Update the status of the drawerToggle icon.
703 drawerToggle.onConfigurationChanged(newConfig);
707 public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
708 // Do nothing because the user selected "Cancel".
712 public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
713 // Get shortcutNameEditText from the alert dialog.
714 EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
716 // Create the bookmark shortcut based on formattedUrlString.
717 Intent bookmarkShortcut = new Intent();
718 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
719 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
721 // Place the bookmark shortcut on the home screen.
722 Intent placeBookmarkShortcut = new Intent();
723 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
724 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
725 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
726 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
727 sendBroadcast(placeBookmarkShortcut);
730 // Override onBackPressed to handle the navigation drawer and mainWebView.
732 public void onBackPressed() {
733 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
735 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
736 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
737 drawerLayout.closeDrawer(GravityCompat.START);
739 // Load the previous URL if available.
740 if (mainWebView.canGoBack()) {
741 mainWebView.goBack();
743 // Pass onBackPressed to the system.
744 super.onBackPressed();
749 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
750 // Get the text from urlTextBox and convert it to a string.
751 String unformattedUrlString = urlTextBox.getText().toString();
752 URL unformattedUrl = null;
753 Uri.Builder formattedUri = new Uri.Builder();
755 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
756 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
757 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
758 if (!unformattedUrlString.startsWith("http")) {
759 unformattedUrlString = "http://" + unformattedUrlString;
762 // 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.
764 unformattedUrl = new URL(unformattedUrlString);
765 } catch (MalformedURLException e) {
769 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
770 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
771 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
772 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
773 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
774 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
776 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
777 formattedUrlString = formattedUri.build().toString();
779 // Sanitize the search input and convert it to a DuckDuckGo search.
780 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
782 // Use the correct search URL based on javaScriptEnabled.
783 if (javaScriptEnabled) {
784 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
786 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
790 mainWebView.loadUrl(formattedUrlString);
792 // Hides the keyboard so we can see the webpage.
793 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
794 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);