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