]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/MainWebViewActivity.java
Update German translation. Finish optional app bar icons implementation.
[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.DialogFragment;
25 import android.app.DownloadManager;
26 import android.content.Intent;
27 import android.content.SharedPreferences;
28 import android.content.res.Configuration;
29 import android.graphics.Bitmap;
30 import android.graphics.drawable.BitmapDrawable;
31 import android.graphics.drawable.Drawable;
32 import android.net.Uri;
33 import android.net.http.SslError;
34 import android.os.Build;
35 import android.os.Bundle;
36 import android.preference.PreferenceManager;
37 import android.support.design.widget.NavigationView;
38 import android.support.design.widget.Snackbar;
39 import android.support.v4.app.ActivityCompat;
40 import android.support.v4.content.ContextCompat;
41 import android.support.v4.view.GravityCompat;
42 import android.support.v4.widget.DrawerLayout;
43 import android.support.v4.widget.SwipeRefreshLayout;
44 import android.support.v7.app.ActionBar;
45 import android.support.v7.app.ActionBarDrawerToggle;
46 import android.support.v7.app.AppCompatActivity;
47 import android.support.v7.widget.Toolbar;
48 import android.util.Patterns;
49 import android.view.KeyEvent;
50 import android.view.Menu;
51 import android.view.MenuItem;
52 import android.view.View;
53 import android.view.inputmethod.InputMethodManager;
54 import android.webkit.CookieManager;
55 import android.webkit.DownloadListener;
56 import android.webkit.SslErrorHandler;
57 import android.webkit.WebChromeClient;
58 import android.webkit.WebStorage;
59 import android.webkit.WebView;
60 import android.webkit.WebViewClient;
61 import android.webkit.WebViewDatabase;
62 import android.widget.EditText;
63 import android.widget.FrameLayout;
64 import android.widget.ImageView;
65 import android.widget.ProgressBar;
66
67 import java.io.UnsupportedEncodingException;
68 import java.net.MalformedURLException;
69 import java.net.URL;
70 import java.net.URLEncoder;
71 import java.util.HashMap;
72 import java.util.Map;
73
74 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
75 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener, SslCertificateError.SslCertificateErrorListener {
76     // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `BookmarksActivity`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
77     // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
78     public static Bitmap favoriteIcon;
79
80     // `privacyBrowserActivity` is public static so it can be accessed from `SettingsFragment`.
81     // It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`,
82     public static Activity privacyBrowserActivity;
83
84     // `mainWebView` is public static so it can be accessed from `SettingsFragment`.
85     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, and `loadUrlFromTextBox()`.
86     public static WebView mainWebView;
87
88     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`.
89     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
90     public static String formattedUrlString;
91
92     // `mainMenu` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreateOptionsMenu()` and `onOptionsItemSelected()`.
93     public static Menu mainMenu;
94
95     // `cookieManager` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
96     public static CookieManager cookieManager;
97
98     // `javaScriptEnabled` is public static so it can be accessed from `SettingsFragment`.
99     // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
100     public static boolean javaScriptEnabled;
101
102     // `firstPartyCookiesEnabled` is public static so it can be accessed from `SettingsFragment`.
103     // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
104     public static boolean firstPartyCookiesEnabled;
105
106     // `thridPartyCookiesEnables` is public static so it can be accessed from `SettingsFragment`.
107     // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
108     public static boolean thirdPartyCookiesEnabled;
109
110     // `domStorageEnabled` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`.
111     public static boolean domStorageEnabled;
112
113     // `saveFormDataEnabled` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`.
114     public static boolean saveFormDataEnabled;
115
116     // `javaScriptDisabledSearchURL` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()` and `loadURLFromTextBox()`.
117     public static String javaScriptDisabledSearchURL;
118
119     // `javaScriptEnabledSearchURL` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()` and `loadURLFromTextBox()`.
120     public static String javaScriptEnabledSearchURL;
121
122     // `homepage` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()` and `onOptionsItemSelected()`.
123     public static String homepage;
124
125     // `swipeToRefresh` is public static so it can be accessed from SettingsFragment.  It is also used in onCreate().
126     public static SwipeRefreshLayout swipeToRefresh;
127
128     // `swipeToRefreshEnabled` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()`.
129     public static boolean swipeToRefreshEnabled;
130
131     // `customHeader` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()` and `loadUrlFromTextBox()`.
132     public static Map<String, String> customHeaders = new HashMap<String, String>();
133
134
135
136     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
137     private ActionBarDrawerToggle drawerToggle;
138
139     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
140     private DrawerLayout drawerLayout;
141
142     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
143     private EditText urlTextBox;
144
145     // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
146     private View adView;
147
148     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
149     private SslErrorHandler sslErrorHandler;
150
151     // `sharedPreferences` is used in `onCreate()` and `onCreateOptionsMenu()`.
152     SharedPreferences sharedPreferences;
153
154     @Override
155     // 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.
156     @SuppressLint("SetJavaScriptEnabled")
157     protected void onCreate(Bundle savedInstanceState) {
158         super.onCreate(savedInstanceState);
159         setContentView(R.layout.main_coordinatorlayout);
160
161         // We need a handle for the activity, which is accessed from `SettingsFragment` and fed into `updatePrivacyIcons()`.
162         privacyBrowserActivity = this;
163
164         // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
165         Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
166         setSupportActionBar(supportAppBar);
167         final ActionBar appBar = getSupportActionBar();
168
169         // This is needed to get rid of the Android Studio warning that appBar might be null.
170         assert appBar != null;
171
172         // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
173         appBar.setCustomView(R.layout.url_bar);
174         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
175
176         // Set the "go" button on the keyboard to load the URL in urlTextBox.
177         urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
178         urlTextBox.setOnKeyListener(new View.OnKeyListener() {
179             public boolean onKey(View v, int keyCode, KeyEvent event) {
180                 // If the event is a key-down event on the "enter" button, load the URL.
181                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
182                     // Load the URL into the mainWebView and consume the event.
183                     try {
184                         loadUrlFromTextBox();
185                     } catch (UnsupportedEncodingException e) {
186                         e.printStackTrace();
187                     }
188                     // If the enter key was pressed, consume the event.
189                     return true;
190                 } else {
191                     // If any other key was pressed, do not consume the event.
192                     return false;
193                 }
194             }
195         });
196
197         final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
198
199         // Implement swipe to refresh
200         swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
201         assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null.
202         swipeToRefresh.setColorSchemeResources(R.color.blue);
203         swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
204             @Override
205             public void onRefresh() {
206                 mainWebView.reload();
207             }
208         });
209
210         mainWebView = (WebView) findViewById(R.id.mainWebView);
211
212         // Create the navigation drawer.
213         drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
214         // The DrawerTitle identifies the drawer in accessibility mode.
215         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
216
217         // Listen for touches on the navigation menu.
218         final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
219         assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null.
220         navigationView.setNavigationItemSelectedListener(this);
221
222         // drawerToggle creates the hamburger icon at the start of the AppBar.
223         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
224
225         // Replace the header that `WebView` creates for `X-Requested-With` with a null value.  The default value is the application ID (com.stoutner.privacybrowser.standard).
226         customHeaders.put("X-Requested-With", "");
227
228         mainWebView.setWebViewClient(new WebViewClient() {
229             // shouldOverrideUrlLoading makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
230             @Override
231             public boolean shouldOverrideUrlLoading(WebView view, String url) {
232                 // Use an external email program if the link begins with "mailto:".
233                 if (url.startsWith("mailto:")) {
234                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
235                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
236
237                     // Parse the url and set it as the data for the `Intent`.
238                     emailIntent.setData(Uri.parse(url));
239
240                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
241                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
242
243                     // Make it so.
244                     startActivity(emailIntent);
245                     return true;
246                 } else {  // Load the URL in Privacy Browser.
247                     mainWebView.loadUrl(url, customHeaders);
248                     return true;
249                 }
250             }
251
252             // Update the URL in urlTextBox when the page starts to load.
253             @Override
254             public void onPageStarted(WebView view, String url, Bitmap favicon) {
255                 urlTextBox.setText(url);
256             }
257
258             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
259             @Override
260             public void onPageFinished(WebView view, String url) {
261                 formattedUrlString = url;
262
263                 // Only update urlTextBox if the user is not typing in it.
264                 if (!urlTextBox.hasFocus()) {
265                     urlTextBox.setText(formattedUrlString);
266                 }
267             }
268
269             // Handle SSL Certificate errors.
270             @Override
271             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
272                 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
273                 sslErrorHandler = handler;
274
275                 // Display the SSL error `AlertDialog`.
276                 DialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
277                 sslCertificateErrorDialogFragment.show(getFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
278             }
279         });
280
281         mainWebView.setWebChromeClient(new WebChromeClient() {
282             // Update the progress bar when a page is loading.
283             @Override
284             public void onProgressChanged(WebView view, int progress) {
285                 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
286                 progressBar.setProgress(progress);
287                 if (progress < 100) {
288                     progressBar.setVisibility(View.VISIBLE);
289                 } else {
290                     progressBar.setVisibility(View.GONE);
291
292                     //Stop the SwipeToRefresh indicator if it is running
293                     swipeToRefresh.setRefreshing(false);
294                 }
295             }
296
297             // Set the favorite icon when it changes.
298             @Override
299             public void onReceivedIcon(WebView view, Bitmap icon) {
300                 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
301                 favoriteIcon = icon;
302
303                 // Place the favorite icon in the appBar.
304                 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
305                 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
306             }
307
308             // Enter full screen video
309             @Override
310             public void onShowCustomView(View view, CustomViewCallback callback) {
311                 appBar.hide();
312
313                 // Show the fullScreenVideoFrameLayout.
314                 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
315                 fullScreenVideoFrameLayout.addView(view);
316                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
317
318                 // Hide the mainWebView.
319                 mainWebView.setVisibility(View.GONE);
320
321                 // Hide the ad if this is the free flavor.
322                 BannerAd.hideAd(adView);
323
324                 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
325                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
326                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
327                  */
328                 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
329             }
330
331             // Exit full screen video
332             public void onHideCustomView() {
333                 appBar.show();
334
335                 // Show the mainWebView.
336                 mainWebView.setVisibility(View.VISIBLE);
337
338                 // Show the ad if this is the free flavor.
339                 BannerAd.showAd(adView);
340
341                 // Hide the fullScreenVideoFrameLayout.
342                 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
343                 fullScreenVideoFrameLayout.removeAllViews();
344                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
345             }
346         });
347
348         // Allow the downloading of files.
349         mainWebView.setDownloadListener(new DownloadListener() {
350             // Launch the Android download manager when a link leads to a download.
351             @Override
352             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
353                 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
354                 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
355
356                 // Add the URL as the description for the download.
357                 requestUri.setDescription(url);
358
359                 // Show the download notification after the download is completed.
360                 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
361
362                 // Initiate the download and display a Snackbar.
363                 downloadManager.enqueue(requestUri);
364                 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
365             }
366         });
367
368         // Allow pinch to zoom.
369         mainWebView.getSettings().setBuiltInZoomControls(true);
370
371         // Hide zoom controls.
372         mainWebView.getSettings().setDisplayZoomControls(false);
373
374
375         // Initialize the default preference values the first time the program is run.
376         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
377
378         // Get the shared preference values.
379         sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
380
381         // Set JavaScript initial status.  The default value is false.
382         javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
383         mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
384
385         // Initialize cookieManager.
386         cookieManager = CookieManager.getInstance();
387
388         // Set cookies initial status.  The default value is false.
389         firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
390         cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
391
392         // Set third-party cookies initial status if API >= 21.  The default value is false.
393         if (Build.VERSION.SDK_INT >= 21) {
394             thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
395             cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
396         }
397
398         // Set DOM storage initial status.  The default value is false.
399         domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
400         mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
401
402         // Set the saved form data initial status.  The default is false.
403         saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
404         mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
405
406         // Set the user agent initial status.
407         String userAgentString = sharedPreferences.getString("user_agent", "Default user agent");
408         switch (userAgentString) {
409             case "Default user agent":
410                 // Do nothing.
411                 break;
412
413             case "Custom user agent":
414                 // Set the custom user agent on mainWebView,  The default is "PrivacyBrowser/1.0".
415                 mainWebView.getSettings().setUserAgentString(sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0"));
416                 break;
417
418             default:
419                 // Set the selected user agent on mainWebView.  The default is "PrivacyBrowser/1.0".
420                 mainWebView.getSettings().setUserAgentString(sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0"));
421                 break;
422         }
423
424         // Set the initial string for JavaScript disabled search.
425         if (sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=").equals("Custom URL")) {
426             // Get the custom URL string.  The default is "".
427             javaScriptDisabledSearchURL = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
428         } else {
429             // Use the string from javascript_disabled_search.
430             javaScriptDisabledSearchURL = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
431         }
432
433         // Set the initial string for JavaScript enabled search.
434         if (sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=").equals("Custom URL")) {
435             // Get the custom URL string.  The default is "".
436             javaScriptEnabledSearchURL = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
437         } else {
438             // Use the string from javascript_enabled_search.
439             javaScriptEnabledSearchURL = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
440         }
441
442
443         // Set the homepage initial status.  The default value is `https://www.duckduckgo.com`.
444         homepage = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
445
446         // Set the font size initial status.  the default value is `100`.
447         String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
448         mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
449
450         // Set the swipe to refresh initial status.  The default is `true`.
451         swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", true);
452         swipeToRefresh.setEnabled(swipeToRefreshEnabled);
453
454
455         // Get the intent information that started the app.
456         final Intent intent = getIntent();
457
458         if (intent.getData() != null) {
459             // Get the intent data and convert it to a string.
460             final Uri intentUriData = intent.getData();
461             formattedUrlString = intentUriData.toString();
462         }
463
464         // If formattedUrlString is null assign the homepage to it.
465         if (formattedUrlString == null) {
466             formattedUrlString = homepage;
467         }
468
469         // Load the initial website.
470         mainWebView.loadUrl(formattedUrlString, customHeaders);
471
472         // If the favorite icon is null, load the default.
473         if (favoriteIcon == null) {
474             // We have to use `ContextCompat` until API >= 21.
475             Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
476             BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
477             favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
478         }
479
480         // Initialize AdView for the free flavor and request an ad.  If this is not the free flavor BannerAd.requestAd() does nothing.
481         adView = findViewById(R.id.adView);
482         BannerAd.requestAd(adView);
483     }
484
485
486     @Override
487     protected void onNewIntent(Intent intent) {
488         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
489         setIntent(intent);
490
491         if (intent.getData() != null) {
492             // Get the intent data and convert it to a string.
493             final Uri intentUriData = intent.getData();
494             formattedUrlString = intentUriData.toString();
495         }
496
497         // Close the navigation drawer if it is open.
498         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
499             drawerLayout.closeDrawer(GravityCompat.START);
500         }
501
502         // Load the website.
503         mainWebView.loadUrl(formattedUrlString, customHeaders);
504
505         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
506         mainWebView.requestFocus();
507     }
508
509     @Override
510     public boolean onCreateOptionsMenu(Menu menu) {
511         // Inflate the menu; this adds items to the action bar if it is present.
512         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
513
514         // Set mainMenu so it can be used by onOptionsItemSelected.
515         mainMenu = menu;
516
517         // Set the initial status of the privacy icon.
518         updatePrivacyIcons(privacyBrowserActivity);
519
520         // Get handles for the menu items.
521         MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
522         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
523         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
524         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
525
526         // Set the initial status of the menu item checkboxes.
527         toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
528         toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
529         toggleDomStorage.setChecked(domStorageEnabled);
530         toggleSaveFormData.setChecked(saveFormDataEnabled);
531
532         // Set the status of the additional app bar icons.  The default is `false`.
533         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
534             toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
535             toggleThirdPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
536             toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
537             toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
538         } else { //Do not display the additional icons.
539             toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
540             toggleThirdPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
541             toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
542             toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
543         }
544
545         return true;
546     }
547
548     @Override
549     public boolean onPrepareOptionsMenu(Menu menu) {
550         // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
551         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
552         if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
553             toggleThirdPartyCookies.setEnabled(true);
554         } else {
555             toggleThirdPartyCookies.setEnabled(false);
556         }
557
558         // Enable DOM Storage if JavaScript is enabled.
559         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
560         toggleDomStorage.setEnabled(javaScriptEnabled);
561
562         // Enable Clear Cookies if there are any.
563         MenuItem clearCookies = menu.findItem(R.id.clearCookies);
564         clearCookies.setEnabled(cookieManager.hasCookies());
565
566         // Enable Clear Form Data is there is any.
567         MenuItem clearFormData = menu.findItem(R.id.clearFormData);
568         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
569         clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
570
571         // Initialize font size variables.
572         int fontSize = mainWebView.getSettings().getTextZoom();
573         String fontSizeTitle;
574         MenuItem selectedFontSizeMenuItem;
575
576         // Prepare the font size title and current size menu item.
577         switch (fontSize) {
578             case 50:
579                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
580                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
581                 break;
582
583             case 75:
584                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
585                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
586                 break;
587
588             case 100:
589                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
590                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
591                 break;
592
593             case 125:
594                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
595                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
596                 break;
597
598             case 150:
599                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
600                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
601                 break;
602
603             case 175:
604                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
605                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
606                 break;
607
608             case 200:
609                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
610                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
611                 break;
612
613             default:
614                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
615                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
616                 break;
617         }
618
619         // Set the font size title and select the current size menu item.
620         MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
621         fontSizeMenuItem.setTitle(fontSizeTitle);
622         selectedFontSizeMenuItem.setChecked(true);
623
624         // Only show `Refresh` if `swipeToRefresh` is disabled.
625         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
626         refreshMenuItem.setVisible(!swipeToRefreshEnabled);
627
628         // Run all the other default commands.
629         super.onPrepareOptionsMenu(menu);
630
631         // `return true` displays the menu.
632         return true;
633     }
634
635     @Override
636     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
637     @SuppressLint("SetJavaScriptEnabled")
638     // removeAllCookies is deprecated, but it is required for API < 21.
639     @SuppressWarnings("deprecation")
640     public boolean onOptionsItemSelected(MenuItem menuItem) {
641         int menuItemId = menuItem.getItemId();
642
643         // Set the commands that relate to the menu entries.
644         switch (menuItemId) {
645             case R.id.toggleJavaScript:
646                 // Switch the status of javaScriptEnabled.
647                 javaScriptEnabled = !javaScriptEnabled;
648
649                 // Apply the new JavaScript status.
650                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
651
652                 // Update the privacy icon.
653                 updatePrivacyIcons(privacyBrowserActivity);
654
655                 // Display a `Snackbar`.
656                 if (javaScriptEnabled) {
657                     Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
658                 } else {
659                     if (firstPartyCookiesEnabled) {
660                         Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
661                     } else {
662                         Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
663                     }
664                 }
665
666                 // Reload the WebView.
667                 mainWebView.reload();
668                 return true;
669
670             case R.id.toggleFirstPartyCookies:
671                 // Switch the status of firstPartyCookiesEnabled.
672                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
673
674                 // Update the menu checkbox.
675                 menuItem.setChecked(firstPartyCookiesEnabled);
676
677                 // Apply the new cookie status.
678                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
679
680                 // Update the privacy icon.
681                 updatePrivacyIcons(privacyBrowserActivity);
682
683                 // Display a `Snackbar`.
684                 if (firstPartyCookiesEnabled) {
685                     Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
686                 } else {
687                     if (javaScriptEnabled) {
688                         Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
689                     } else {
690                         Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
691                     }
692                 }
693
694                 // Reload the WebView.
695                 mainWebView.reload();
696                 return true;
697
698             case R.id.toggleThirdPartyCookies:
699                 if (Build.VERSION.SDK_INT >= 21) {
700                     // Switch the status of thirdPartyCookiesEnabled.
701                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
702
703                     // Update the menu checkbox.
704                     menuItem.setChecked(thirdPartyCookiesEnabled);
705
706                     // Apply the new cookie status.
707                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
708
709                     // Display a `Snackbar`.
710                     if (thirdPartyCookiesEnabled) {
711                         Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
712                     } else {
713                         Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
714                     }
715
716                     // Reload the WebView.
717                     mainWebView.reload();
718                 } // Else do nothing because SDK < 21.
719                 return true;
720
721             case R.id.toggleDomStorage:
722                 // Switch the status of domStorageEnabled.
723                 domStorageEnabled = !domStorageEnabled;
724
725                 // Update the menu checkbox.
726                 menuItem.setChecked(domStorageEnabled);
727
728                 // Apply the new DOM Storage status.
729                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
730
731                 // Display a `Snackbar`.
732                 if (domStorageEnabled) {
733                     Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
734                 } else {
735                     Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
736                 }
737
738                 // Reload the WebView.
739                 mainWebView.reload();
740                 return true;
741
742             case R.id.toggleSaveFormData:
743                 // Switch the status of saveFormDataEnabled.
744                 saveFormDataEnabled = !saveFormDataEnabled;
745
746                 // Update the menu checkbox.
747                 menuItem.setChecked(saveFormDataEnabled);
748
749                 // Apply the new form data status.
750                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
751
752                 // Display a `Snackbar`.
753                 if (saveFormDataEnabled) {
754                     Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
755                 } else {
756                     Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
757                 }
758
759                 // Reload the WebView.
760                 mainWebView.reload();
761                 return true;
762
763             case R.id.clearCookies:
764                 if (Build.VERSION.SDK_INT < 21) {
765                     cookieManager.removeAllCookie();
766                 } else {
767                     cookieManager.removeAllCookies(null);
768                 }
769                 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
770                 return true;
771
772             case R.id.clearDomStorage:
773                 WebStorage webStorage = WebStorage.getInstance();
774                 webStorage.deleteAllData();
775                 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
776                 return true;
777
778             case R.id.clearFormData:
779                 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
780                 mainWebViewDatabase.clearFormData();
781                 mainWebView.reload();
782                 return true;
783
784             case R.id.fontSizeFiftyPercent:
785                 mainWebView.getSettings().setTextZoom(50);
786                 return true;
787
788             case R.id.fontSizeSeventyFivePercent:
789                 mainWebView.getSettings().setTextZoom(75);
790                 return true;
791
792             case R.id.fontSizeOneHundredPercent:
793                 mainWebView.getSettings().setTextZoom(100);
794                 return true;
795
796             case R.id.fontSizeOneHundredTwentyFivePercent:
797                 mainWebView.getSettings().setTextZoom(125);
798                 return true;
799
800             case R.id.fontSizeOneHundredFiftyPercent:
801                 mainWebView.getSettings().setTextZoom(150);
802                 return true;
803
804             case R.id.fontSizeOneHundredSeventyFivePercent:
805                 mainWebView.getSettings().setTextZoom(175);
806                 return true;
807
808             case R.id.fontSizeTwoHundredPercent:
809                 mainWebView.getSettings().setTextZoom(200);
810                 return true;
811
812             case R.id.share:
813                 Intent shareIntent = new Intent();
814                 shareIntent.setAction(Intent.ACTION_SEND);
815                 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
816                 shareIntent.setType("text/plain");
817                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
818                 return true;
819
820             case R.id.addToHomescreen:
821                 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `@string/create_shortcut`.
822                 DialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
823                 createHomeScreenShortcutDialogFragment.show(getFragmentManager(), getResources().getString(R.string.create_shortcut));
824
825                 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
826                 return true;
827
828             case R.id.refresh:
829                 mainWebView.reload();
830                 return true;
831
832             default:
833                 // Don't consume the event.
834                 return super.onOptionsItemSelected(menuItem);
835         }
836     }
837
838     @Override
839     // removeAllCookies is deprecated, but it is required for API < 21.
840     @SuppressWarnings("deprecation")
841     public boolean onNavigationItemSelected(MenuItem menuItem) {
842         int menuItemId = menuItem.getItemId();
843
844         switch (menuItemId) {
845             case R.id.home:
846                 mainWebView.loadUrl(homepage, customHeaders);
847                 break;
848
849             case R.id.back:
850                 if (mainWebView.canGoBack()) {
851                     mainWebView.goBack();
852                 }
853                 break;
854
855             case R.id.forward:
856                 if (mainWebView.canGoForward()) {
857                     mainWebView.goForward();
858                 }
859                 break;
860
861             case R.id.bookmarks:
862                 // Launch BookmarksActivity.
863                 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
864                 startActivity(bookmarksIntent);
865                 break;
866
867             case R.id.downloads:
868                 // Launch the system Download Manager.
869                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
870
871                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
872                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
873
874                 startActivity(downloadManagerIntent);
875                 break;
876
877             case R.id.settings:
878                 // Launch `SettingsActivity`.
879                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
880                 startActivity(settingsIntent);
881                 break;
882
883             case R.id.guide:
884                 // Launch `GuideActivity`.
885                 Intent guideIntent = new Intent(this, GuideActivity.class);
886                 startActivity(guideIntent);
887                 break;
888
889             case R.id.about:
890                 // Launch `AboutActivity`.
891                 Intent aboutIntent = new Intent(this, AboutActivity.class);
892                 startActivity(aboutIntent);
893                 break;
894
895             case R.id.clearAndExit:
896                 // Clear cookies.  The commands changed slightly in API 21.
897                 if (Build.VERSION.SDK_INT >= 21) {
898                     cookieManager.removeAllCookies(null);
899                 } else {
900                     cookieManager.removeAllCookie();
901                 }
902
903                 // Clear DOM storage.
904                 WebStorage domStorage = WebStorage.getInstance();
905                 domStorage.deleteAllData();
906
907                 // Clear form data.
908                 WebViewDatabase formData = WebViewDatabase.getInstance(this);
909                 formData.clearFormData();
910
911                 // Clear cache.  The argument of "true" includes disk files.
912                 mainWebView.clearCache(true);
913
914                 // Clear the back/forward history.
915                 mainWebView.clearHistory();
916
917                 // Clear any SSL certificate preferences.
918                 MainWebViewActivity.mainWebView.clearSslPreferences();
919
920                 // Clear `formattedUrlString`.
921                 formattedUrlString = null;
922
923                 // Destroy the internal state of the webview.
924                 mainWebView.destroy();
925
926                 // Close Privacy Browser.  finishAndRemoveTask also removes Privacy Browser from the recent app list.
927                 if (Build.VERSION.SDK_INT >= 21) {
928                     finishAndRemoveTask();
929                 } else {
930                     finish();
931                 }
932                 break;
933
934             default:
935                 break;
936         }
937
938         // Close the navigation drawer.
939         drawerLayout.closeDrawer(GravityCompat.START);
940         return true;
941     }
942
943     @Override
944     public void onPostCreate(Bundle savedInstanceState) {
945         super.onPostCreate(savedInstanceState);
946
947         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
948         drawerToggle.syncState();
949     }
950
951     @Override
952     public void onConfigurationChanged(Configuration newConfig) {
953         super.onConfigurationChanged(newConfig);
954
955         // Reload the ad if this is the free flavor.
956         BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
957
958         // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
959         adView = findViewById(R.id.adView);
960
961         // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug:  https://code.google.com/p/android/issues/detail?id=20493#c8
962         invalidateOptionsMenu();
963     }
964
965     @Override
966     public void onCancelCreateHomeScreenShortcut(DialogFragment dialogFragment) {
967         // Do nothing because the user selected "Cancel".
968     }
969
970     @Override
971     public void onCreateHomeScreenShortcut(DialogFragment dialogFragment) {
972         // Get shortcutNameEditText from the alert dialog.
973         EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
974
975         // Create the bookmark shortcut based on formattedUrlString.
976         Intent bookmarkShortcut = new Intent();
977         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
978         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
979
980         // Place the bookmark shortcut on the home screen.
981         Intent placeBookmarkShortcut = new Intent();
982         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
983         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
984         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
985         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
986         sendBroadcast(placeBookmarkShortcut);
987     }
988
989     public void viewSslCertificate(View view) {
990         // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
991         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
992         viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
993     }
994
995     @Override
996     public void onSslErrorCancel() {
997         sslErrorHandler.cancel();
998     }
999
1000     @Override
1001     public void onSslErrorProceed() {
1002         sslErrorHandler.proceed();
1003     }
1004
1005     // Override onBackPressed to handle the navigation drawer and mainWebView.
1006     @Override
1007     public void onBackPressed() {
1008         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
1009
1010         // Close the navigation drawer if it is available.  GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1011         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1012             drawerLayout.closeDrawer(GravityCompat.START);
1013         } else {
1014             // Load the previous URL if available.
1015             assert mainWebView != null; //This assert removes the incorrect warning in Android Studio on the following line that mainWebView might be null.
1016             if (mainWebView.canGoBack()) {
1017                 mainWebView.goBack();
1018             } else {
1019                 // Pass onBackPressed to the system.
1020                 super.onBackPressed();
1021             }
1022         }
1023     }
1024
1025     @Override
1026     public void onPause() {
1027         // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
1028         BannerAd.pauseAd(adView);
1029
1030         super.onPause();
1031     }
1032
1033     @Override
1034     public void onResume() {
1035         super.onResume();
1036
1037         // We need to resume the adView for the free flavor.
1038         BannerAd.resumeAd(adView);
1039     }
1040
1041     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1042         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
1043         String unformattedUrlString = urlTextBox.getText().toString().trim();
1044
1045         URL unformattedUrl = null;
1046         Uri.Builder formattedUri = new Uri.Builder();
1047
1048         // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
1049         if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1050             // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
1051             if (!unformattedUrlString.startsWith("http")) {
1052                 unformattedUrlString = "http://" + unformattedUrlString;
1053             }
1054
1055             // 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.
1056             try {
1057                 unformattedUrl = new URL(unformattedUrlString);
1058             } catch (MalformedURLException e) {
1059                 e.printStackTrace();
1060             }
1061
1062             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1063             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1064             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1065             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1066             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1067             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1068
1069             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1070             formattedUrlString = formattedUri.build().toString();
1071         } else {
1072             // Sanitize the search input and convert it to a DuckDuckGo search.
1073             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1074
1075             // Use the correct search URL based on javaScriptEnabled.
1076             if (javaScriptEnabled) {
1077                 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1078             } else { // JavaScript is disabled.
1079                 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1080             }
1081         }
1082
1083         mainWebView.loadUrl(formattedUrlString, customHeaders);
1084
1085         // Hides the keyboard so we can see the webpage.
1086         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
1087         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1088     }
1089
1090     public static void updatePrivacyIcons(Activity activity) {
1091         // Get handles for the icons.
1092         MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1093         MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1094         MenuItem thirdPartyCookiesIcon = mainMenu.findItem(R.id.toggleThirdPartyCookies);
1095         MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1096         MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1097
1098         // Update `privacyIcon`.
1099         if (javaScriptEnabled) {
1100             // `JavaScript` is enabled.
1101             privacyIcon.setIcon(R.drawable.javascript_enabled);
1102         } else {
1103             if (firstPartyCookiesEnabled) {
1104                 // `JavaScript` is disabled but cookies are enabled.
1105                 privacyIcon.setIcon(R.drawable.warning);
1106             } else {
1107                 // All the dangerous features are disabled.
1108                 privacyIcon.setIcon(R.drawable.privacy_mode);
1109             }
1110         }
1111
1112         // Update `firstPartyCookiesIcon`.
1113         if (firstPartyCookiesEnabled) {
1114             // First-party cookies are enabled.
1115             firstPartyCookiesIcon.setIcon(R.drawable.cookies_warning);
1116         } else {
1117             // First-party cookies are disabled.
1118             firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1119         }
1120
1121         // Update `thirdPartyCookiesIcon`.
1122         if (firstPartyCookiesEnabled) {
1123             if (thirdPartyCookiesEnabled) {
1124                 //  Third-party cookies are enabled.  Bad!
1125                 thirdPartyCookiesIcon.setIcon(R.drawable.cookies_critical);
1126             } else {
1127                 // Third-party cookies are disabled.
1128                 thirdPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1129             }
1130         } else {
1131             // First-party cookies are disabled, so third-party cookies are ghosted.
1132             thirdPartyCookiesIcon.setIcon(R.drawable.cookies_ghosted);
1133         }
1134
1135         // Update `domStorageIcon`.
1136         if (javaScriptEnabled) {
1137             if (domStorageEnabled) {
1138                 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1139             } else {
1140                 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1141             }
1142         } else {
1143             domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1144         }
1145
1146         // Update `formDataIcon`.
1147         if (saveFormDataEnabled) {
1148             formDataIcon.setIcon(R.drawable.form_data_enabled);
1149         } else {
1150             formDataIcon.setIcon(R.drawable.form_data_disabled);
1151         }
1152
1153         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.
1154         ActivityCompat.invalidateOptionsMenu(activity);
1155     }
1156 }