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