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