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