]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/MainWebViewActivity.java
13600840837ef20d245fd564cc742abda5dcf82c
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / MainWebViewActivity.java
1 /**
2  * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 package com.stoutner.privacybrowser;
21
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;
60
61 import java.io.UnsupportedEncodingException;
62 import java.net.MalformedURLException;
63 import java.net.URL;
64 import java.net.URLEncoder;
65
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.  It is also used in onCreate(), onOptionsItemSelected(), onNavigationItemSelected(), and loadUrlFromTextBox().
71     public static WebView mainWebView;
72
73     // drawerToggle is used in onCreate(), onPostCreate(), onConfigurationChanged(), onNewIntent(), and onNavigationItemSelected().
74     private ActionBarDrawerToggle drawerToggle;
75     // drawerLayout is used in onCreate(), onNewIntent(), and onBackPressed().
76     private DrawerLayout drawerLayout;
77     // mainMenu is used in onCreateOptionsMenu() and onOptionsItemSelected().
78     private Menu mainMenu;
79     // formattedUrlString is used in onCreate(), onOptionsItemSelected(), onCreateHomeScreenShortcutCreate(), and loadUrlFromTextBox().
80     private String formattedUrlString;
81     // homepage is used in onCreate() and onOptionsItemSelected().
82     private String homepage;
83     // javaScriptEnabled is used in onCreate(), onCreateOptionsMenu(), onOptionsItemSelected(), and loadUrlFromTextBox().
84     private boolean javaScriptEnabled;
85     // domStorageEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
86     private boolean domStorageEnabled;
87
88     /* saveFormDataEnabled does nothing until database storage is implemented.
89     // saveFormDataEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
90     private boolean saveFormDataEnabled;
91     */
92
93     // cookieManager is used in onCreate(), onOptionsItemSelected(), and onNavigationItemSelected().
94     private CookieManager cookieManager;
95     // cookiesEnabled is used in onCreate(), onCreateOptionsMenu(), and onOptionsItemSelected().
96     private boolean cookiesEnabled;
97
98     // urlTextBox is used in onCreate(), onOptionsItemSelected(), and loadUrlFromTextBox().
99     private EditText urlTextBox;
100
101     @Override
102     // 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.
103     @SuppressLint("SetJavaScriptEnabled")
104     protected void onCreate(Bundle savedInstanceState) {
105         super.onCreate(savedInstanceState);
106         setContentView(R.layout.coordinator_layout);
107
108         // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
109         Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
110         setSupportActionBar(supportAppBar);
111
112         final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
113
114         // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
115         final ActionBar appBar = getSupportActionBar();
116
117         // Setup AdView for the free flavor.
118         final View adView = findViewById(R.id.adView);
119
120         // Implement swipe to refresh
121         final SwipeRefreshLayout swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
122         swipeToRefresh.setColorSchemeResources(R.color.blue);
123         swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
124             @Override
125             public void onRefresh() {
126                 mainWebView.reload();
127             }
128         });
129
130         mainWebView = (WebView) findViewById(R.id.mainWebView);
131
132         if (appBar != null) {
133             // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
134             appBar.setCustomView(R.layout.url_bar);
135             appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
136
137             // Set the "go" button on the keyboard to load the URL in urlTextBox.
138             urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
139             urlTextBox.setOnKeyListener(new View.OnKeyListener() {
140                 public boolean onKey(View v, int keyCode, KeyEvent event) {
141                     // If the event is a key-down event on the "enter" button, load the URL.
142                     if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
143                         // Load the URL into the mainWebView and consume the event.
144                         try {
145                             loadUrlFromTextBox();
146                         } catch (UnsupportedEncodingException e) {
147                             e.printStackTrace();
148                         }
149                         // If the enter key was pressed, consume the event.
150                         return true;
151                     } else {
152                         // If any other key was pressed, do not consume the event.
153                         return false;
154                     }
155                 }
156             });
157         }
158
159         // Create the navigation drawer.
160         drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
161         // The DrawerTitle identifies the drawer in accessibility mode.
162         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
163
164         // Listen for touches on the navigation menu.
165         final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
166         navigationView.setNavigationItemSelectedListener(this);
167
168         // drawerToggle creates the hamburger icon at the start of the AppBar.
169         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
170
171         mainWebView.setWebViewClient(new WebViewClient() {
172             // shouldOverrideUrlLoading makes this WebView the default handler for URLs inside the app, so that links are not kicked out to other apps.
173             @Override
174             public boolean shouldOverrideUrlLoading(WebView view, String url) {
175                 mainWebView.loadUrl(url);
176                 return true;
177             }
178
179             // Update the URL in urlTextBox when the page starts to load.
180             @Override
181             public void onPageStarted(WebView view, String url, Bitmap favicon) {
182                 urlTextBox.setText(url);
183             }
184
185             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
186             @Override
187             public void onPageFinished(WebView view, String url) {
188                 formattedUrlString = url;
189
190                 // Only update urlTextBox if the user is not typing in it.
191                 if (!urlTextBox.hasFocus()) {
192                     urlTextBox.setText(formattedUrlString);
193                 }
194             }
195         });
196
197         mainWebView.setWebChromeClient(new WebChromeClient() {
198             // Update the progress bar when a page is loading.
199             @Override
200             public void onProgressChanged(WebView view, int progress) {
201                 // Make sure that appBar is not null.
202                 if (appBar != null) {
203                     ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
204                     progressBar.setProgress(progress);
205                     if (progress < 100) {
206                         progressBar.setVisibility(View.VISIBLE);
207                     } else {
208                         progressBar.setVisibility(View.GONE);
209
210                         //Stop the SwipeToRefresh indicator if it is running
211                         swipeToRefresh.setRefreshing(false);
212                     }
213                 }
214             }
215
216             // Set the favorite icon when it changes.
217             @Override
218             public void onReceivedIcon(WebView view, Bitmap icon) {
219                 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
220                 favoriteIcon = icon;
221
222                 // Place the favorite icon in the appBar if it is not null.
223                 if (appBar != null) {
224                     ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
225                     imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
226                 }
227             }
228
229             // Enter full screen video
230             @Override
231             public void onShowCustomView(View view, CustomViewCallback callback) {
232                 if (appBar != null) {
233                     appBar.hide();
234                 }
235
236                 // Show the fullScreenVideoFrameLayout.
237                 fullScreenVideoFrameLayout.addView(view);
238                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
239
240                 // Hide the mainWebView.
241                 mainWebView.setVisibility(View.GONE);
242
243                 // Hide the ad if this is the free flavor.
244                 BannerAd.hideAd(adView);
245
246                 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
247                 ** SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
248                 ** SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
249                 */
250
251                 // Set the one flag supported by API >= 14.
252                 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
253
254                 // Set the two flags that are supported by API >= 16.
255                 if (Build.VERSION.SDK_INT >= 16) {
256                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN);
257                 }
258
259                 // Set all three flags that are supported by API >= 19.
260                 if (Build.VERSION.SDK_INT >= 19) {
261                     view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
262                 }
263             }
264
265             // Exit full screen video
266             public void onHideCustomView() {
267                 if (appBar != null) {
268                     appBar.show();
269                 }
270
271                 // Show the mainWebView.
272                 mainWebView.setVisibility(View.VISIBLE);
273
274                 // Show the ad if this is the free flavor.
275                 BannerAd.showAd(adView);
276
277                 // Hide the fullScreenVideoFrameLayout.
278                 fullScreenVideoFrameLayout.removeAllViews();
279                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
280             }
281         });
282
283         // Allow the downloading of files.
284         mainWebView.setDownloadListener(new DownloadListener() {
285             // Launch the Android download manager when a link leads to a download.
286             @Override
287             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
288                 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
289                 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
290
291                 // Add the URL as the description for the download.
292                 requestUri.setDescription(url);
293
294                 // Show the download notification after the download is completed.
295                 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
296
297                 // Initiate the download and display a Snackbar.
298                 downloadManager.enqueue(requestUri);
299                 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
300             }
301         });
302
303         // Allow pinch to zoom.
304         mainWebView.getSettings().setBuiltInZoomControls(true);
305
306         // Hide zoom controls.
307         mainWebView.getSettings().setDisplayZoomControls(false);
308
309         // Initialize the default preference values the first time the program is run.
310         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
311
312         // Get the shared preference values.
313         SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
314
315         // Set JavaScript initial status.
316         javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
317         mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
318
319         // Set DOM storage initial status.
320         domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
321         mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
322
323         /* Save Form Data does nothing until database storage is implemented.
324         // Set Save Form Data initial status.
325         saveFormDataEnabled = true;
326         mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
327         */
328
329         // Set cookies initial status.
330         cookiesEnabled = savedPreferences.getBoolean("cookies_enabled", false);
331         cookieManager = CookieManager.getInstance();
332         cookieManager.setAcceptCookie(cookiesEnabled);
333
334         // Set homepage initial status.
335         homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
336
337         // Get the intent information that started the app.
338         final Intent intent = getIntent();
339
340         if (intent.getData() != null) {
341             // Get the intent data and convert it to a string.
342             final Uri intentUriData = intent.getData();
343             formattedUrlString = intentUriData.toString();
344         }
345
346         // If formattedUrlString is null assign the homepage to it.
347         if (formattedUrlString == null) {
348             formattedUrlString = homepage;
349         }
350
351         // Load the initial website.
352         mainWebView.loadUrl(formattedUrlString);
353
354         // Load the ad if this is the free flavor.
355         BannerAd.requestAd(adView);
356     }
357
358     @Override
359     protected void onNewIntent(Intent intent) {
360         // Sets the new intent as the activity intent, so that any future getIntent()s pick up this one instead of creating a new activity.
361         setIntent(intent);
362
363         if (intent.getData() != null) {
364             // Get the intent data and convert it to a string.
365             final Uri intentUriData = intent.getData();
366             formattedUrlString = intentUriData.toString();
367         }
368
369         // Close the navigation drawer if it is open.
370         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
371             drawerLayout.closeDrawer(GravityCompat.START);
372         }
373
374         // Load the website.
375         mainWebView.loadUrl(formattedUrlString);
376
377         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
378         mainWebView.requestFocus();
379     }
380
381     @Override
382     public boolean onCreateOptionsMenu(Menu menu) {
383         // Inflate the menu; this adds items to the action bar if it is present.
384         getMenuInflater().inflate(R.menu.menu_options, menu);
385
386         // Set mainMenu so it can be used by onOptionsItemSelected.
387         mainMenu = menu;
388
389         // Get MenuItems for checkable menu items.
390         MenuItem toggleJavaScript = menu.findItem(R.id.toggleJavaScript);
391         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
392         /* toggleSaveFormData does nothing until database storage is implemented.
393         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
394         */
395         MenuItem toggleCookies = menu.findItem(R.id.toggleCookies);
396
397         // Set the initial icon for toggleJavaScript
398         if (javaScriptEnabled) {
399             toggleJavaScript.setIcon(R.drawable.javascript_enabled);
400         } else {
401             if (domStorageEnabled || cookiesEnabled) {
402                 toggleJavaScript.setIcon(R.drawable.warning);
403             } else {
404                 toggleJavaScript.setIcon(R.drawable.privacy_mode);
405             }
406         }
407
408         // Set the initial status of the menu item checkboxes.
409         toggleDomStorage.setChecked(domStorageEnabled);
410         /* toggleSaveFormData does nothing until database storage is implemented.
411         toggleSaveFormData.setChecked(saveFormDataEnabled);
412         */
413         toggleCookies.setChecked(cookiesEnabled);
414
415         return true;
416     }
417
418     @Override
419     public boolean onPrepareOptionsMenu(Menu menu) {
420         // Enable Clear Cookies if there are any.
421         MenuItem clearCookies = menu.findItem(R.id.clearCookies);
422         clearCookies.setEnabled(cookieManager.hasCookies());
423
424         // Run all the other default commands.
425         super.onPrepareOptionsMenu(menu);
426
427         // return true displays the menu.
428         return true;
429     }
430
431     @Override
432     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
433     @SuppressLint("SetJavaScriptEnabled")
434     // removeAllCookies is deprecated, but it is required for API < 21.
435     @SuppressWarnings("deprecation")
436     public boolean onOptionsItemSelected(MenuItem menuItem) {
437         int menuItemId = menuItem.getItemId();
438
439         // Some options need to update the drawable for toggleJavaScript.
440         MenuItem toggleJavaScript = mainMenu.findItem(R.id.toggleJavaScript);
441
442         // Set the commands that relate to the menu entries.
443         switch (menuItemId) {
444             case R.id.toggleJavaScript:
445                 if (javaScriptEnabled) {
446                     javaScriptEnabled = false;
447                     mainWebView.getSettings().setJavaScriptEnabled(false);
448                     mainWebView.reload();
449
450                     // Update the toggleJavaScript icon and display a snackbar.
451                     if (domStorageEnabled || cookiesEnabled) {
452                         menuItem.setIcon(R.drawable.warning);
453                         if (domStorageEnabled && cookiesEnabled) {
454                             Snackbar.make(findViewById(R.id.mainWebView), R.string.both_still_enabled, Snackbar.LENGTH_SHORT).show();
455                         } else {
456                             if (domStorageEnabled) {
457                                 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_still_enabled, Snackbar.LENGTH_SHORT).show();
458                             } else {
459                                 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_still_enabled, Snackbar.LENGTH_SHORT).show();
460                             }
461                         }
462                     } else {
463                         menuItem.setIcon(R.drawable.privacy_mode);
464                         Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
465                     }
466                 } else {
467                     javaScriptEnabled = true;
468                     menuItem.setIcon(R.drawable.javascript_enabled);
469                     mainWebView.getSettings().setJavaScriptEnabled(true);
470                     mainWebView.reload();
471                     Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
472                 }
473                 return true;
474
475             case R.id.toggleDomStorage:
476                 if (domStorageEnabled) {
477                     domStorageEnabled = false;
478                     menuItem.setChecked(false);
479                     mainWebView.getSettings().setDomStorageEnabled(false);
480                     mainWebView.reload();
481
482                     // Update the toggleJavaScript icon and display a snackbar if appropriate.
483                     if (!javaScriptEnabled && !cookiesEnabled) {
484                         toggleJavaScript.setIcon(R.drawable.privacy_mode);
485                         Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
486                     } else {
487                         if (cookiesEnabled) {
488                             toggleJavaScript.setIcon(R.drawable.warning);
489                             Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_still_enabled, Snackbar.LENGTH_SHORT).show();
490                         } // Else Do nothing because JavaScript is enabled.
491                     }
492                 } else {
493                     domStorageEnabled = true;
494                     menuItem.setChecked(true);
495                     mainWebView.getSettings().setDomStorageEnabled(true);
496                     mainWebView.reload();
497
498                     // Update the toggleJavaScript icon if appropriate.
499                     if (!javaScriptEnabled) {
500                         toggleJavaScript.setIcon(R.drawable.warning);
501                     } // Else Do nothing because JavaScript is enabled.
502
503                     Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
504                 }
505                 return true;
506
507             /* toggleSaveFormData does nothing until database storage is implemented.
508             case R.id.toggleSaveFormData:
509                 if (saveFormDataEnabled) {
510                     saveFormDataEnabled = false;
511                     menuItem.setChecked(false);
512                     mainWebView.getSettings().setSaveFormData(false);
513                     mainWebView.reload();
514                 } else {
515                     saveFormDataEnabled = true;
516                     menuItem.setChecked(true);
517                     mainWebView.getSettings().setSaveFormData(true);
518                     mainWebView.reload();
519                 }
520                 return true;
521             */
522
523             case R.id.toggleCookies:
524                 if (cookiesEnabled) {
525                     cookiesEnabled = false;
526                     menuItem.setChecked(false);
527                     cookieManager.setAcceptCookie(false);
528                     mainWebView.reload();
529
530                     // Update the toggleJavaScript icon and display a snackbar if appropriate.
531                     if (!javaScriptEnabled && !domStorageEnabled) {
532                         toggleJavaScript.setIcon(R.drawable.privacy_mode);
533                         Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
534                     } else {
535                         if (domStorageEnabled) {
536                             toggleJavaScript.setIcon(R.drawable.warning);
537                             Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
538                         } // Else Do nothing because JavaScript is enabled.
539                     }
540                 } else {
541                     cookiesEnabled = true;
542                     menuItem.setChecked(true);
543                     cookieManager.setAcceptCookie(true);
544                     mainWebView.reload();
545
546                     // Update the toggleJavaScript icon if appropriate.
547                     if (!javaScriptEnabled) {
548                         toggleJavaScript.setIcon(R.drawable.warning);
549                     } // Else Do nothing because JavaScript is enabled.
550
551                     Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_enabled, Snackbar.LENGTH_SHORT).show();
552                 }
553                 return true;
554
555             case R.id.clearDomStorage:
556                 WebStorage webStorage = WebStorage.getInstance();
557                 webStorage.deleteAllData();
558                 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
559                 return true;
560
561             case R.id.clearCookies:
562                 if (Build.VERSION.SDK_INT < 21) {
563                     cookieManager.removeAllCookie();
564                 } else {
565                     cookieManager.removeAllCookies(null);
566                 }
567                 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
568                 return true;
569
570             case R.id.share:
571                 Intent shareIntent = new Intent();
572                 shareIntent.setAction(Intent.ACTION_SEND);
573                 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
574                 shareIntent.setType("text/plain");
575                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
576                 return true;
577
578             case R.id.addToHomescreen:
579                 // Show the CreateHomeScreenShortcut AlertDialog and name this instance createShortcut.
580                 AppCompatDialogFragment shortcutDialog = new CreateHomeScreenShortcut();
581                 shortcutDialog.show(getSupportFragmentManager(), "createShortcut");
582
583                 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
584                 return true;
585
586             default:
587                 return super.onOptionsItemSelected(menuItem);
588         }
589     }
590
591     @Override
592     // removeAllCookies is deprecated, but it is required for API < 21.
593     @SuppressWarnings("deprecation")
594     public boolean onNavigationItemSelected(MenuItem menuItem) {
595         int menuItemId = menuItem.getItemId();
596
597         switch (menuItemId) {
598             case R.id.home:
599                 mainWebView.loadUrl(homepage);
600                 break;
601
602             case R.id.back:
603                 if (mainWebView.canGoBack()) {
604                     mainWebView.goBack();
605                 }
606                 break;
607
608             case R.id.forward:
609                 if (mainWebView.canGoForward()) {
610                     mainWebView.goForward();
611                 }
612                 break;
613
614             case R.id.downloads:
615                 // Launch the system Download Manager.
616                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
617
618                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
619                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
620
621                 startActivity(downloadManagerIntent);
622                 break;
623
624             case R.id.settings:
625                 // Launch SettingsActivity.
626                 Intent intent = new Intent(this, SettingsActivity.class);
627                 startActivity(intent);
628                 break;
629
630             case R.id.about:
631                 // Show the AboutDialog AlertDialog and name this instance aboutDialog.
632                 AppCompatDialogFragment aboutDialog = new AboutDialog();
633                 aboutDialog.show(getSupportFragmentManager(), "aboutDialog");
634                 break;
635
636             case R.id.clearAndExit:
637                 // Clear DOM storage.
638                 WebStorage domStorage = WebStorage.getInstance();
639                 domStorage.deleteAllData();
640
641                 // Clear cookies.  The commands changed slightly in API 21.
642                 if (Build.VERSION.SDK_INT >= 21) {
643                     cookieManager.removeAllCookies(null);
644                 } else {
645                     cookieManager.removeAllCookie();
646                 }
647
648                 // Destroy the internal state of the webview.
649                 mainWebView.destroy();
650
651                 // Close Privacy Browser.  finishAndRemoveTask also removes Privacy Browser from the recent app list.
652                 if (Build.VERSION.SDK_INT >= 21) {
653                     finishAndRemoveTask();
654                 } else {
655                     finish();
656                 }
657                 break;
658
659             default:
660                 break;
661         }
662
663         // Close the navigation drawer.
664         drawerLayout.closeDrawer(GravityCompat.START);
665         return true;
666     }
667
668     @Override
669     public void onPostCreate(Bundle savedInstanceState) {
670         super.onPostCreate(savedInstanceState);
671
672         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
673         drawerToggle.syncState();
674     }
675
676     @Override
677     public void onConfigurationChanged(Configuration newConfig) {
678         super.onConfigurationChanged(newConfig);
679
680         // Update the status of the drawerToggle icon.
681         drawerToggle.onConfigurationChanged(newConfig);
682     }
683
684     @Override
685     public void onCreateHomeScreenShortcutCancel(DialogFragment dialog) {
686         // Do nothing because the user selected "Cancel".
687     }
688
689     @Override
690     public void onCreateHomeScreenShortcutCreate(DialogFragment dialog) {
691         // Get shortcutNameEditText from the alert dialog.
692         EditText shortcutNameEditText = (EditText) dialog.getDialog().findViewById(R.id.shortcutNameEditText);
693
694         // Create the bookmark shortcut based on formattedUrlString.
695         Intent bookmarkShortcut = new Intent();
696         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
697         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
698
699         // Place the bookmark shortcut on the home screen.
700         Intent placeBookmarkShortcut = new Intent();
701         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
702         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
703         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
704         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
705         sendBroadcast(placeBookmarkShortcut);
706     }
707
708     // Override onBackPressed to handle the navigation drawer and mainWebView.
709     @Override
710     public void onBackPressed() {
711         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
712
713         // Close the navigation drawer if it is available.  GravityCompat.START is the drawer on the left on Left-to-Right layout text.
714         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
715             drawerLayout.closeDrawer(GravityCompat.START);
716         } else {
717             // Load the previous URL if available.
718             if (mainWebView.canGoBack()) {
719                 mainWebView.goBack();
720             } else {
721                 // Pass onBackPressed to the system.
722                 super.onBackPressed();
723             }
724         }
725     }
726
727     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
728         // Get the text from urlTextBox and convert it to a string.
729         String unformattedUrlString = urlTextBox.getText().toString();
730         URL unformattedUrl = null;
731         Uri.Builder formattedUri = new Uri.Builder();
732
733         // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
734         if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
735             // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
736             if (!unformattedUrlString.startsWith("http")) {
737                 unformattedUrlString = "http://" + unformattedUrlString;
738             }
739
740             // 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.
741             try {
742                 unformattedUrl = new URL(unformattedUrlString);
743             } catch (MalformedURLException e) {
744                 e.printStackTrace();
745             }
746
747             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
748             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
749             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
750             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
751             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
752             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
753
754             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
755             formattedUrlString = formattedUri.build().toString();
756         } else {
757             // Sanitize the search input and convert it to a DuckDuckGo search.
758             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
759
760             // Use the correct search URL based on javaScriptEnabled.
761             if (javaScriptEnabled) {
762                 formattedUrlString = "https://duckduckgo.com/?q=" + encodedUrlString;
763             } else {
764                 formattedUrlString = "https://duckduckgo.com/html/?q=" + encodedUrlString;
765             }
766         }
767
768         mainWebView.loadUrl(formattedUrlString);
769
770         // Hides the keyboard so we can see the webpage.
771         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
772         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
773     }
774 }