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