Change the default user-agent to `PrivacyBrowser/1.0`.
[PrivacyBrowser.git] / app / src / main / java / com / stoutner / privacybrowser / activities / MainWebView.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.activities;
21
22 import android.annotation.SuppressLint;
23 import android.app.DialogFragment;
24 import android.app.DownloadManager;
25 import android.content.Context;
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.print.PrintDocumentAdapter;
39 import android.print.PrintManager;
40 import android.support.annotation.NonNull;
41 import android.support.design.widget.CoordinatorLayout;
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.text.Editable;
55 import android.text.TextWatcher;
56 import android.util.Patterns;
57 import android.view.ContextMenu;
58 import android.view.GestureDetector;
59 import android.view.KeyEvent;
60 import android.view.Menu;
61 import android.view.MenuItem;
62 import android.view.MotionEvent;
63 import android.view.View;
64 import android.view.WindowManager;
65 import android.view.inputmethod.InputMethodManager;
66 import android.webkit.CookieManager;
67 import android.webkit.DownloadListener;
68 import android.webkit.SslErrorHandler;
69 import android.webkit.WebBackForwardList;
70 import android.webkit.WebChromeClient;
71 import android.webkit.WebStorage;
72 import android.webkit.WebView;
73 import android.webkit.WebViewClient;
74 import android.webkit.WebViewDatabase;
75 import android.widget.EditText;
76 import android.widget.FrameLayout;
77 import android.widget.ImageView;
78 import android.widget.LinearLayout;
79 import android.widget.ProgressBar;
80 import android.widget.RelativeLayout;
81 import android.widget.TextView;
82
83 import com.stoutner.privacybrowser.BannerAd;
84 import com.stoutner.privacybrowser.BuildConfig;
85 import com.stoutner.privacybrowser.R;
86 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
87 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcut;
88 import com.stoutner.privacybrowser.dialogs.DownloadFile;
89 import com.stoutner.privacybrowser.dialogs.DownloadImage;
90 import com.stoutner.privacybrowser.dialogs.SslCertificateError;
91 import com.stoutner.privacybrowser.dialogs.UrlHistory;
92 import com.stoutner.privacybrowser.dialogs.ViewSslCertificate;
93
94 import java.io.UnsupportedEncodingException;
95 import java.net.MalformedURLException;
96 import java.net.URL;
97 import java.net.URLEncoder;
98 import java.util.HashMap;
99 import java.util.Map;
100
101 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
102 public class MainWebView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
103         SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener, DownloadImage.DownloadImageListener, UrlHistory.UrlHistoryListener {
104
105     // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
106     // It is also used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
107     public static ActionBar appBar;
108
109     // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `Bookmarks`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
110     // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
111     public static Bitmap favoriteIcon;
112
113     // `formattedUrlString` is public static so it can be accessed from `Bookmarks`.
114     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
115     public static String formattedUrlString;
116
117     // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`.  It is also used in `onCreate()`.
118     public static SslCertificate sslCertificate;
119
120
121
122     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
123     private DrawerLayout drawerLayout;
124
125     // `rootCoordinatorLayout` is used in `onCreate()` and `applySettings()`.
126     private CoordinatorLayout rootCoordinatorLayout;
127
128     // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
129     private WebView mainWebView;
130
131     // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
132     private EditText findOnPageEditText;
133
134     // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
135     private FrameLayout fullScreenVideoFrameLayout;
136
137     // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
138     private SwipeRefreshLayout swipeRefreshLayout;
139
140     // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, and `onRestart()`.
141     private CookieManager cookieManager;
142
143     // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrlFromTextBox()`.
144     private final Map<String, String> customHeaders = new HashMap<>();
145
146     // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
147     // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
148     private Boolean javaScriptEnabled;
149
150     // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
151     private boolean firstPartyCookiesEnabled;
152
153     // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
154     private boolean thirdPartyCookiesEnabled;
155
156     // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
157     private boolean domStorageEnabled;
158
159     // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
160     private boolean saveFormDataEnabled;
161
162     // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
163     private boolean swipeToRefreshEnabled;
164
165     // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
166     private String homepage;
167
168     // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
169     private String javaScriptDisabledSearchURL;
170
171     // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
172     private String javaScriptEnabledSearchURL;
173
174     // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
175     private boolean hideSystemBarsOnFullscreen;
176
177     // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
178     private boolean translucentNavigationBarOnFullscreen;
179
180     // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
181     private Menu mainMenu;
182
183     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
184     private ActionBarDrawerToggle drawerToggle;
185
186     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
187     private EditText urlTextBox;
188
189     // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
190     private View adView;
191
192     // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
193     private SslErrorHandler sslErrorHandler;
194
195     // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
196     private InputMethodManager inputMethodManager;
197
198     @Override
199     // 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.
200     @SuppressLint("SetJavaScriptEnabled")
201     protected void onCreate(Bundle savedInstanceState) {
202         super.onCreate(savedInstanceState);
203         setContentView(R.layout.drawerlayout);
204
205         // Get a handle for `inputMethodManager`.
206         inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
207
208         // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
209         Toolbar supportAppBar = (Toolbar) findViewById(R.id.app_bar);
210         setSupportActionBar(supportAppBar);
211         appBar = getSupportActionBar();
212
213         // This is needed to get rid of the Android Studio warning that `appBar` might be null.
214         assert appBar != null;
215
216         // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
217         appBar.setCustomView(R.layout.url_app_bar);
218         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
219
220         // Set the "go" button on the keyboard to load the URL in urlTextBox.
221         urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
222         urlTextBox.setOnKeyListener(new View.OnKeyListener() {
223             @Override
224             public boolean onKey(View v, int keyCode, KeyEvent event) {
225                 // If the event is a key-down event on the `enter` button, load the URL.
226                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
227                     // Load the URL into the mainWebView and consume the event.
228                     try {
229                         loadUrlFromTextBox();
230                     } catch (UnsupportedEncodingException e) {
231                         e.printStackTrace();
232                     }
233                     // If the enter key was pressed, consume the event.
234                     return true;
235                 } else {
236                     // If any other key was pressed, do not consume the event.
237                     return false;
238                 }
239             }
240         });
241
242         // Get handles for views that need to be accessed.
243         drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
244         rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
245         mainWebView = (WebView) findViewById(R.id.mainWebView);
246         findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
247         fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
248
249         // Create a double-tap listener to toggle full-screen mode.
250         final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
251             // Override `onDoubleTap()`.  All other events are handled using the default settings.
252             @Override
253             public boolean onDoubleTap(MotionEvent event) {
254                 if (appBar.isShowing()) {  // If `appBar` is visible, switch to full screen mode.
255                     // Hide the `appBar`.
256                     appBar.hide();
257
258                     // Hide the `BannerAd` in the free flavor.
259                     if (BuildConfig.FLAVOR.contentEquals("free")) {
260                         BannerAd.hideAd(adView);
261                     }
262
263                     // Modify the system bars.
264                     if (hideSystemBarsOnFullscreen) {  // Hide everything.
265                         // Remove the translucent overlays.
266                         getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
267
268                         // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
269                         drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
270
271                         /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
272                          * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
273                          * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
274                          */
275                         rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
276
277                         // Set `rootCoordinatorLayout` to fill the whole screen.
278                         rootCoordinatorLayout.setFitsSystemWindows(false);
279                     } else {  // Hide everything except the status and navigation bars.
280                         // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
281                         rootCoordinatorLayout.setFitsSystemWindows(false);
282
283                         if (translucentNavigationBarOnFullscreen) {  // There is an Android Support Library bug that causes a scrim to print on the right side of the `Drawer Layout` when the navigation bar is displayed on the right of the screen.
284                             // Set the navigation bar to be translucent.
285                             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
286                         }
287                     }
288                 } else {  // Switch to normal viewing mode.
289                     // Show the `appBar`.
290                     appBar.show();
291
292                     // Show the `BannerAd` in the free flavor.
293                     if (BuildConfig.FLAVOR.contentEquals("free")) {
294                         // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
295                         BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
296
297                         // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
298                         adView = findViewById(R.id.adView);
299                     }
300
301                     // Remove the translucent navigation bar flag if it is set.
302                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
303
304                     // Add the translucent status flag if it is unset.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
305                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
306
307                     // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
308                     rootCoordinatorLayout.setSystemUiVisibility(0);
309
310                     // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
311                     rootCoordinatorLayout.setFitsSystemWindows(true);
312                 }
313
314                 // Consume the double-tap.
315                 return true;
316             }
317         });
318
319         // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
320         mainWebView.setOnTouchListener(new View.OnTouchListener() {
321             @Override
322             public boolean onTouch(View v, MotionEvent event) {
323                 // Send the `event` to `gestureDetector`.
324                 return gestureDetector.onTouchEvent(event);
325             }
326         });
327
328         // Update `findOnPageCountTextView`.
329         mainWebView.setFindListener(new WebView.FindListener() {
330             // Get a handle for `findOnPageCountTextView`.
331             final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
332
333             @Override
334             public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
335                 if ((isDoneCounting) && (numberOfMatches == 0)) {  // There are no matches.
336                     // Set `findOnPageCountTextView` to `0/0`.
337                     findOnPageCountTextView.setText(R.string.zero_of_zero);
338                 } else if (isDoneCounting) {  // There are matches.
339                     // `activeMatchOrdinal` is zero-based.
340                     int activeMatch = activeMatchOrdinal + 1;
341
342                     // Set `findOnPageCountTextView`.
343                     findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
344                 }
345             }
346         });
347
348         // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
349         findOnPageEditText.addTextChangedListener(new TextWatcher() {
350             @Override
351             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
352                 // Do nothing.
353             }
354
355             @Override
356             public void onTextChanged(CharSequence s, int start, int before, int count) {
357                 // Do nothing.
358             }
359
360             @Override
361             public void afterTextChanged(Editable s) {
362                 // Search for the text in `mainWebView`.
363                 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
364             }
365         });
366
367         // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
368         findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
369             @Override
370             public boolean onKey(View v, int keyCode, KeyEvent event) {
371                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {  // The `enter` key was pressed.
372                     // Hide the soft keyboard.  `0` indicates no additional flags.
373                     inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
374
375                     // Consume the event.
376                     return true;
377                 } else {  // A different key was pressed.
378                     // Do not consume the event.
379                     return false;
380                 }
381             }
382         });
383
384         // Implement swipe to refresh
385         swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
386         swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
387         swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
388             @Override
389             public void onRefresh() {
390                 mainWebView.reload();
391             }
392         });
393
394         // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
395         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
396
397         // Listen for touches on the navigation menu.
398         final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
399         navigationView.setNavigationItemSelectedListener(this);
400
401         // Get handles for `navigationMenu` and the back and forward menu items.  The menu is zero-based, so items 1, 2, and 3 are the second, third, and fourth entries in the menu.
402         final Menu navigationMenu = navigationView.getMenu();
403         final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
404         final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
405         final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
406
407         // The `DrawerListener` allows us to update the Navigation Menu.
408         drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
409             @Override
410             public void onDrawerSlide(View drawerView, float slideOffset) {
411             }
412
413             @Override
414             public void onDrawerOpened(View drawerView) {
415             }
416
417             @Override
418             public void onDrawerClosed(View drawerView) {
419             }
420
421             @Override
422             public void onDrawerStateChanged(int newState) {
423                 // Update the `Back`, `Forward`, and `History` menu items every time the drawer opens.
424                 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
425                 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
426                 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
427
428                 // Hide the keyboard so we can see the navigation menu.  `0` indicates no additional flags.
429                 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
430             }
431         });
432
433         // drawerToggle creates the hamburger icon at the start of the AppBar.
434         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
435
436         mainWebView.setWebViewClient(new WebViewClient() {
437             // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
438             // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
439             @SuppressWarnings("deprecation")
440             @Override
441             public boolean shouldOverrideUrlLoading(WebView view, String url) {
442                 // Use an external email program if the link begins with `mailto:`.
443                 if (url.startsWith("mailto:")) {
444                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
445                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
446
447                     // Parse the url and set it as the data for the `Intent`.
448                     emailIntent.setData(Uri.parse(url));
449
450                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
451                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
452
453                     // Make it so.
454                     startActivity(emailIntent);
455                     return true;
456                 } else {  // Load the URL in Privacy Browser.
457                     mainWebView.loadUrl(url, customHeaders);
458                     return true;
459                 }
460             }
461
462             // Update the URL in urlTextBox when the page starts to load.
463             @Override
464             public void onPageStarted(WebView view, String url, Bitmap favicon) {
465                 // 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.
466                 formattedUrlString = url;
467
468                 // Display the loading URL is the URL text box.
469                 urlTextBox.setText(url);
470             }
471
472             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
473             @Override
474             public void onPageFinished(WebView view, String url) {
475                 formattedUrlString = url;
476
477                 // Only update urlTextBox if the user is not typing in it.
478                 if (!urlTextBox.hasFocus()) {
479                     urlTextBox.setText(formattedUrlString);
480                 }
481
482                 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
483                 sslCertificate = mainWebView.getCertificate();
484             }
485
486             // Handle SSL Certificate errors.
487             @Override
488             public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
489                 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
490                 sslErrorHandler = handler;
491
492                 // Display the SSL error `AlertDialog`.
493                 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
494                 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
495             }
496         });
497
498         mainWebView.setWebChromeClient(new WebChromeClient() {
499             // Update the progress bar when a page is loading.
500             @Override
501             public void onProgressChanged(WebView view, int progress) {
502                 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
503                 progressBar.setProgress(progress);
504                 if (progress < 100) {
505                     progressBar.setVisibility(View.VISIBLE);
506                 } else {
507                     progressBar.setVisibility(View.GONE);
508
509                     //Stop the `SwipeToRefresh` indicator if it is running
510                     swipeRefreshLayout.setRefreshing(false);
511                 }
512             }
513
514             // Set the favorite icon when it changes.
515             @Override
516             public void onReceivedIcon(WebView view, Bitmap icon) {
517                 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
518                 favoriteIcon = icon;
519
520                 // Place the favorite icon in the appBar.
521                 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
522                 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
523             }
524
525             // Enter full screen video
526             @Override
527             public void onShowCustomView(View view, CustomViewCallback callback) {
528                 // Pause the ad if this is the free flavor.
529                 if (BuildConfig.FLAVOR.contentEquals("free")) {
530                     BannerAd.pauseAd(adView);
531                 }
532
533                 // Remove the translucent overlays.
534                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
535
536                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
537                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
538
539                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
540                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
541                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
542                  */
543                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
544
545                 // Set `rootCoordinatorLayout` to fill the entire screen.
546                 rootCoordinatorLayout.setFitsSystemWindows(false);
547
548                 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
549                 fullScreenVideoFrameLayout.addView(view);
550                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
551             }
552
553             // Exit full screen video
554             public void onHideCustomView() {
555                 // Hide `fullScreenVideoFrameLayout`.
556                 fullScreenVideoFrameLayout.removeAllViews();
557                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
558
559                 // Add the translucent status flag.  This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
560                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
561
562                 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars.  This also clears the `SYSTEM_UI` flags.
563                 rootCoordinatorLayout.setFitsSystemWindows(true);
564
565                 // Show the ad if this is the free flavor.
566                 if (BuildConfig.FLAVOR.contentEquals("free")) {
567                     // Reload the ad.  Because the screen may have rotated, we need to use `reloadAfterRotate`.
568                     BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
569
570                     // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
571                     adView = findViewById(R.id.adView);
572                 }
573             }
574         });
575
576         // Register `mainWebView` for a context menu.  This is used to see link targets and download images.
577         registerForContextMenu(mainWebView);
578
579         // Allow the downloading of files.
580         mainWebView.setDownloadListener(new DownloadListener() {
581             @Override
582             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
583                 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
584                 AppCompatDialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
585                 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
586             }
587         });
588
589         // Allow pinch to zoom.
590         mainWebView.getSettings().setBuiltInZoomControls(true);
591
592         // Hide zoom controls.
593         mainWebView.getSettings().setDisplayZoomControls(false);
594
595         // Initialize cookieManager.
596         cookieManager = CookieManager.getInstance();
597
598         // 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).
599         customHeaders.put("X-Requested-With", "");
600
601         // Initialize the default preference values the first time the program is run.
602         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
603
604         // Apply the settings from the shared preferences.
605         applySettings();
606
607         // Get the intent information that started the app.
608         final Intent intent = getIntent();
609
610         if (intent.getData() != null) {
611             // Get the intent data and convert it to a string.
612             final Uri intentUriData = intent.getData();
613             formattedUrlString = intentUriData.toString();
614         }
615
616         // If formattedUrlString is null assign the homepage to it.
617         if (formattedUrlString == null) {
618             formattedUrlString = homepage;
619         }
620
621         // Load the initial website.
622         mainWebView.loadUrl(formattedUrlString, customHeaders);
623
624         // If the favorite icon is null, load the default.
625         if (favoriteIcon == null) {
626             // We have to use `ContextCompat` until API >= 21.
627             Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
628             BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
629             favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
630         }
631
632         // Initialize AdView for the free flavor and request an ad.  If this is not the free flavor BannerAd.requestAd() does nothing.
633         adView = findViewById(R.id.adView);
634         BannerAd.requestAd(adView);
635     }
636
637
638     @Override
639     protected void onNewIntent(Intent intent) {
640         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
641         setIntent(intent);
642
643         if (intent.getData() != null) {
644             // Get the intent data and convert it to a string.
645             final Uri intentUriData = intent.getData();
646             formattedUrlString = intentUriData.toString();
647         }
648
649         // Close the navigation drawer if it is open.
650         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
651             drawerLayout.closeDrawer(GravityCompat.START);
652         }
653
654         // Load the website.
655         mainWebView.loadUrl(formattedUrlString, customHeaders);
656
657         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
658         mainWebView.requestFocus();
659     }
660
661     @Override
662     public boolean onCreateOptionsMenu(Menu menu) {
663         // Inflate the menu; this adds items to the action bar if it is present.
664         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
665
666         // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
667         mainMenu = menu;
668
669         // Set the initial status of the privacy icons.  `false` does not call `invalidateOptionsMenu` as the last step.
670         updatePrivacyIcons(false);
671
672         // Get handles for the menu items.
673         MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
674         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
675         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
676         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
677
678         // Only display third-Party Cookies if SDK >= 21
679         toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
680
681         // Get the shared preference values.  `this` references the current context.
682         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
683
684         // Set the status of the additional app bar icons.  The default is `false`.
685         if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
686             toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
687             toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
688             toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
689         } else { //Do not display the additional icons.
690             toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
691             toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
692             toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
693         }
694
695         return true;
696     }
697
698     @Override
699     public boolean onPrepareOptionsMenu(Menu menu) {
700         // Get handles for the menu items.
701         MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
702         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
703         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
704         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
705         MenuItem clearCookies = menu.findItem(R.id.clearCookies);
706         MenuItem clearFormData = menu.findItem(R.id.clearFormData);
707         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
708
709         // Set the status of the menu item checkboxes.
710         toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
711         toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
712         toggleDomStorage.setChecked(domStorageEnabled);
713         toggleSaveFormData.setChecked(saveFormDataEnabled);
714
715         // Enable third-party cookies if first-party cookies are enabled.
716         toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
717
718         // Enable DOM Storage if JavaScript is enabled.
719         toggleDomStorage.setEnabled(javaScriptEnabled);
720
721         // Enable Clear Cookies if there are any.
722         clearCookies.setEnabled(cookieManager.hasCookies());
723
724         // Enable Clear Form Data is there is any.
725         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
726         clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
727
728         // Only show `Refresh` if `swipeToRefresh` is disabled.
729         refreshMenuItem.setVisible(!swipeToRefreshEnabled);
730
731         // Initialize font size variables.
732         int fontSize = mainWebView.getSettings().getTextZoom();
733         String fontSizeTitle;
734         MenuItem selectedFontSizeMenuItem;
735
736         // Prepare the font size title and current size menu item.
737         switch (fontSize) {
738             case 50:
739                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
740                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
741                 break;
742
743             case 75:
744                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
745                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
746                 break;
747
748             case 100:
749                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
750                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
751                 break;
752
753             case 125:
754                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
755                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
756                 break;
757
758             case 150:
759                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
760                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
761                 break;
762
763             case 175:
764                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
765                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
766                 break;
767
768             case 200:
769                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
770                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
771                 break;
772
773             default:
774                 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
775                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
776                 break;
777         }
778
779         // Set the font size title and select the current size menu item.
780         MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
781         fontSizeMenuItem.setTitle(fontSizeTitle);
782         selectedFontSizeMenuItem.setChecked(true);
783
784         // Run all the other default commands.
785         super.onPrepareOptionsMenu(menu);
786
787         // `return true` displays the menu.
788         return true;
789     }
790
791     @Override
792     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
793     @SuppressLint("SetJavaScriptEnabled")
794     // removeAllCookies is deprecated, but it is required for API < 21.
795     @SuppressWarnings("deprecation")
796     public boolean onOptionsItemSelected(MenuItem menuItem) {
797         int menuItemId = menuItem.getItemId();
798
799         // Set the commands that relate to the menu entries.
800         switch (menuItemId) {
801             case R.id.toggleJavaScript:
802                 // Switch the status of javaScriptEnabled.
803                 javaScriptEnabled = !javaScriptEnabled;
804
805                 // Apply the new JavaScript status.
806                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
807
808                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
809                 updatePrivacyIcons(true);
810
811                 // Display a `Snackbar`.
812                 if (javaScriptEnabled) {  // JavaScrip is enabled.
813                     Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
814                 } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled, but first-party cookies are enabled.
815                     Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
816                 } else {  // Privacy mode.
817                     Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
818                 }
819
820                 // Reload the WebView.
821                 mainWebView.reload();
822                 return true;
823
824             case R.id.toggleFirstPartyCookies:
825                 // Switch the status of firstPartyCookiesEnabled.
826                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
827
828                 // Update the menu checkbox.
829                 menuItem.setChecked(firstPartyCookiesEnabled);
830
831                 // Apply the new cookie status.
832                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
833
834                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
835                 updatePrivacyIcons(true);
836
837                 // Display a `Snackbar`.
838                 if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
839                     Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
840                 } else if (javaScriptEnabled){  // JavaScript is still enabled.
841                     Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
842                 } else {  // Privacy mode.
843                     Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
844                 }
845
846                 // Reload the WebView.
847                 mainWebView.reload();
848                 return true;
849
850             case R.id.toggleThirdPartyCookies:
851                 if (Build.VERSION.SDK_INT >= 21) {
852                     // Switch the status of thirdPartyCookiesEnabled.
853                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
854
855                     // Update the menu checkbox.
856                     menuItem.setChecked(thirdPartyCookiesEnabled);
857
858                     // Apply the new cookie status.
859                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
860
861                     // Display a `Snackbar`.
862                     if (thirdPartyCookiesEnabled) {
863                         Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
864                     } else {
865                         Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
866                     }
867
868                     // Reload the WebView.
869                     mainWebView.reload();
870                 } // Else do nothing because SDK < 21.
871                 return true;
872
873             case R.id.toggleDomStorage:
874                 // Switch the status of domStorageEnabled.
875                 domStorageEnabled = !domStorageEnabled;
876
877                 // Update the menu checkbox.
878                 menuItem.setChecked(domStorageEnabled);
879
880                 // Apply the new DOM Storage status.
881                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
882
883                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
884                 updatePrivacyIcons(true);
885
886                 // Display a `Snackbar`.
887                 if (domStorageEnabled) {
888                     Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
889                 } else {
890                     Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
891                 }
892
893                 // Reload the WebView.
894                 mainWebView.reload();
895                 return true;
896
897             case R.id.toggleSaveFormData:
898                 // Switch the status of saveFormDataEnabled.
899                 saveFormDataEnabled = !saveFormDataEnabled;
900
901                 // Update the menu checkbox.
902                 menuItem.setChecked(saveFormDataEnabled);
903
904                 // Apply the new form data status.
905                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
906
907                 // Display a `Snackbar`.
908                 if (saveFormDataEnabled) {
909                     Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
910                 } else {
911                     Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
912                 }
913
914                 // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
915                 updatePrivacyIcons(true);
916
917                 // Reload the WebView.
918                 mainWebView.reload();
919                 return true;
920
921             case R.id.clearCookies:
922                 if (Build.VERSION.SDK_INT < 21) {
923                     cookieManager.removeAllCookie();
924                 } else {
925                     cookieManager.removeAllCookies(null);
926                 }
927                 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
928                 return true;
929
930             case R.id.clearDomStorage:
931                 WebStorage webStorage = WebStorage.getInstance();
932                 webStorage.deleteAllData();
933                 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
934                 return true;
935
936             case R.id.clearFormData:
937                 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
938                 mainWebViewDatabase.clearFormData();
939                 mainWebView.reload();
940                 return true;
941
942             case R.id.fontSizeFiftyPercent:
943                 mainWebView.getSettings().setTextZoom(50);
944                 return true;
945
946             case R.id.fontSizeSeventyFivePercent:
947                 mainWebView.getSettings().setTextZoom(75);
948                 return true;
949
950             case R.id.fontSizeOneHundredPercent:
951                 mainWebView.getSettings().setTextZoom(100);
952                 return true;
953
954             case R.id.fontSizeOneHundredTwentyFivePercent:
955                 mainWebView.getSettings().setTextZoom(125);
956                 return true;
957
958             case R.id.fontSizeOneHundredFiftyPercent:
959                 mainWebView.getSettings().setTextZoom(150);
960                 return true;
961
962             case R.id.fontSizeOneHundredSeventyFivePercent:
963                 mainWebView.getSettings().setTextZoom(175);
964                 return true;
965
966             case R.id.fontSizeTwoHundredPercent:
967                 mainWebView.getSettings().setTextZoom(200);
968                 return true;
969
970             case R.id.find_on_page:
971                 // Hide the URL app bar.
972                 Toolbar appBarToolbar = (Toolbar) findViewById(R.id.app_bar);
973                 appBarToolbar.setVisibility(View.GONE);
974
975                 // Show the Find on Page `RelativeLayout`.
976                 LinearLayout findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
977                 findOnPageLinearLayout.setVisibility(View.VISIBLE);
978
979                 // Display the keyboard.  We have to wait 200 ms before running the command to work around a bug in Android.
980                 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
981                 findOnPageEditText.postDelayed(new Runnable()
982                 {
983                     @Override
984                     public void run()
985                     {
986                         // Set the focus on `findOnPageEditText`.
987                         findOnPageEditText.requestFocus();
988
989                         // Display the keyboard.
990                         inputMethodManager.showSoftInput(findOnPageEditText, 0);
991                     }
992                 }, 200);
993                 return true;
994
995             case R.id.share:
996                 Intent shareIntent = new Intent();
997                 shareIntent.setAction(Intent.ACTION_SEND);
998                 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
999                 shareIntent.setType("text/plain");
1000                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1001                 return true;
1002
1003             case R.id.addToHomescreen:
1004                 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `R.string.create_shortcut`.
1005                 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
1006                 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1007
1008                 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
1009                 return true;
1010
1011             case R.id.print:
1012                 // Get a `PrintManager` instance.
1013                 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1014
1015                 // Convert `mainWebView` to `printDocumentAdapter`.
1016                 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1017
1018                 // Print the document.  The print attributes are `null`.
1019                 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1020                 return true;
1021
1022             case R.id.refresh:
1023                 mainWebView.reload();
1024                 return true;
1025
1026             default:
1027                 // Don't consume the event.
1028                 return super.onOptionsItemSelected(menuItem);
1029         }
1030     }
1031
1032     // removeAllCookies is deprecated, but it is required for API < 21.
1033     @SuppressWarnings("deprecation")
1034     @Override
1035     public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1036         int menuItemId = menuItem.getItemId();
1037
1038         switch (menuItemId) {
1039             case R.id.home:
1040                 mainWebView.loadUrl(homepage, customHeaders);
1041                 break;
1042
1043             case R.id.back:
1044                 if (mainWebView.canGoBack()) {
1045                     mainWebView.goBack();
1046                 }
1047                 break;
1048
1049             case R.id.forward:
1050                 if (mainWebView.canGoForward()) {
1051                     mainWebView.goForward();
1052                 }
1053                 break;
1054
1055             case R.id.history:
1056                 // Gte the `WebBackForwardList`.
1057                 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1058
1059                 // Show the `UrlHistory` `AlertDialog` and name this instance `R.string.history`.  `this` is the `Context`.
1060                 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistory.loadBackForwardList(this, webBackForwardList);
1061                 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1062                 break;
1063
1064             case R.id.bookmarks:
1065                 // Launch Bookmarks.
1066                 Intent bookmarksIntent = new Intent(this, Bookmarks.class);
1067                 startActivity(bookmarksIntent);
1068                 break;
1069
1070             case R.id.downloads:
1071                 // Launch the system Download Manager.
1072                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1073
1074                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1075                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1076
1077                 startActivity(downloadManagerIntent);
1078                 break;
1079
1080             case R.id.settings:
1081                 // Launch `Settings`.
1082                 Intent settingsIntent = new Intent(this, Settings.class);
1083                 startActivity(settingsIntent);
1084                 break;
1085
1086             case R.id.guide:
1087                 // Launch `Guide`.
1088                 Intent guideIntent = new Intent(this, Guide.class);
1089                 startActivity(guideIntent);
1090                 break;
1091
1092             case R.id.about:
1093                 // Launch `About`.
1094                 Intent aboutIntent = new Intent(this, About.class);
1095                 startActivity(aboutIntent);
1096                 break;
1097
1098             case R.id.clearAndExit:
1099                 // Clear cookies.  The commands changed slightly in API 21.
1100                 if (Build.VERSION.SDK_INT >= 21) {
1101                     cookieManager.removeAllCookies(null);
1102                 } else {
1103                     cookieManager.removeAllCookie();
1104                 }
1105
1106                 // Clear DOM storage.
1107                 WebStorage domStorage = WebStorage.getInstance();
1108                 domStorage.deleteAllData();
1109
1110                 // Clear form data.
1111                 WebViewDatabase formData = WebViewDatabase.getInstance(this);
1112                 formData.clearFormData();
1113
1114                 // Clear cache.  The argument of "true" includes disk files.
1115                 mainWebView.clearCache(true);
1116
1117                 // Clear the back/forward history.
1118                 mainWebView.clearHistory();
1119
1120                 // Clear any SSL certificate preferences.
1121                 mainWebView.clearSslPreferences();
1122
1123                 // Clear `formattedUrlString`.
1124                 formattedUrlString = null;
1125
1126                 // Clear `customHeaders`.
1127                 customHeaders.clear();
1128
1129                 // Detach all views from `mainWebViewRelativeLayout`.
1130                 RelativeLayout mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.mainWebViewRelativeLayout);
1131                 mainWebViewRelativeLayout.removeAllViews();
1132
1133                 // Destroy the internal state of `mainWebView`.
1134                 mainWebView.destroy();
1135
1136                 // Close Privacy Browser.  `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1137                 if (Build.VERSION.SDK_INT >= 21) {
1138                     finishAndRemoveTask();
1139                 } else {
1140                     finish();
1141                 }
1142
1143                 // Remove the terminated program from RAM.  The status code is `0`.
1144                 System.exit(0);
1145                 break;
1146
1147             default:
1148                 break;
1149         }
1150
1151         // Close the navigation drawer.
1152         drawerLayout.closeDrawer(GravityCompat.START);
1153         return true;
1154     }
1155
1156     @Override
1157     public void onPostCreate(Bundle savedInstanceState) {
1158         super.onPostCreate(savedInstanceState);
1159
1160         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1161         drawerToggle.syncState();
1162     }
1163
1164     @Override
1165     public void onConfigurationChanged(Configuration newConfig) {
1166         super.onConfigurationChanged(newConfig);
1167
1168         // Reload the ad for the free flavor if we are not in full screen mode.
1169         if (BuildConfig.FLAVOR.contentEquals("free") && adView.isShown() && !fullScreenVideoFrameLayout.isShown()) {
1170             // Reload the ad.
1171             BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1172
1173             // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1174             adView = findViewById(R.id.adView);
1175         }
1176
1177         // `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
1178         // ActivityCompat.invalidateOptionsMenu(this);
1179     }
1180
1181     @Override
1182     public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1183         // Store the `HitTestResult`.
1184         final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1185
1186         // Create strings.
1187         final String imageUrl;
1188         final String linkUrl;
1189
1190         switch (hitTestResult.getType()) {
1191             // `SRC_ANCHOR_TYPE` is a link.
1192             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1193                 // Get the target URL.
1194                 linkUrl = hitTestResult.getExtra();
1195
1196                 // Set the target URL as the title of the `ContextMenu`.
1197                 menu.setHeaderTitle(linkUrl);
1198
1199                 // Add a `Load URL` button.
1200                 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1201                     @Override
1202                     public boolean onMenuItemClick(MenuItem item) {
1203                         mainWebView.loadUrl(linkUrl, customHeaders);
1204                         return false;
1205                     }
1206                 });
1207
1208                 // Add a `Cancel` button, which by default closes the `ContextMenu`.
1209                 menu.add(R.string.cancel);
1210                 break;
1211
1212             case WebView.HitTestResult.EMAIL_TYPE:
1213                 // Get the target URL.
1214                 linkUrl = hitTestResult.getExtra();
1215
1216                 // Set the target URL as the title of the `ContextMenu`.
1217                 menu.setHeaderTitle(linkUrl);
1218
1219                 // Add a `Write Email` button.
1220                 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1221                     @Override
1222                     public boolean onMenuItemClick(MenuItem item) {
1223                         // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1224                         Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1225
1226                         // Parse the url and set it as the data for the `Intent`.
1227                         emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1228
1229                         // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1230                         emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1231
1232                         // Make it so.
1233                         startActivity(emailIntent);
1234                         return false;
1235                     }
1236                 });
1237
1238                 // Add a `Cancel` button, which by default closes the `ContextMenu`.
1239                 menu.add(R.string.cancel);
1240                 break;
1241
1242             // `IMAGE_TYPE` is an image.
1243             case WebView.HitTestResult.IMAGE_TYPE:
1244                 // Get the image URL.
1245                 imageUrl = hitTestResult.getExtra();
1246
1247                 // Set the image URL as the title of the `ContextMenu`.
1248                 menu.setHeaderTitle(imageUrl);
1249
1250                 // Add a `View Image` button.
1251                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1252                     @Override
1253                     public boolean onMenuItemClick(MenuItem item) {
1254                         mainWebView.loadUrl(imageUrl, customHeaders);
1255                         return false;
1256                     }
1257                 });
1258
1259                 // Add a `Download Image` button.
1260                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1261                     @Override
1262                     public boolean onMenuItemClick(MenuItem item) {
1263                         // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1264                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1265                         downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1266                         return false;
1267                     }
1268                 });
1269
1270                 // Add a `Cancel` button, which by default closes the `ContextMenu`.
1271                 menu.add(R.string.cancel);
1272                 break;
1273
1274
1275             // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1276             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1277                 // Get the image URL.
1278                 imageUrl = hitTestResult.getExtra();
1279
1280                 // Set the image URL as the title of the `ContextMenu`.
1281                 menu.setHeaderTitle(imageUrl);
1282
1283                 // Add a `View Image` button.
1284                 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1285                     @Override
1286                     public boolean onMenuItemClick(MenuItem item) {
1287                         mainWebView.loadUrl(imageUrl, customHeaders);
1288                         return false;
1289                     }
1290                 });
1291
1292                 // Add a `Download Image` button.
1293                 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1294                     @Override
1295                     public boolean onMenuItemClick(MenuItem item) {
1296                         // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1297                         AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1298                         downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1299                         return false;
1300                     }
1301                 });
1302
1303                 // Add a `Cancel` button, which by default closes the `ContextMenu`.
1304                 menu.add(R.string.cancel);
1305                 break;
1306         }
1307     }
1308
1309     @Override
1310     public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1311         // Get shortcutNameEditText from the alert dialog.
1312         EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1313
1314         // Create the bookmark shortcut based on formattedUrlString.
1315         Intent bookmarkShortcut = new Intent();
1316         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1317         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1318
1319         // Place the bookmark shortcut on the home screen.
1320         Intent placeBookmarkShortcut = new Intent();
1321         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1322         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1323         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1324         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1325         sendBroadcast(placeBookmarkShortcut);
1326     }
1327
1328     @Override
1329     public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1330         // Get a handle for the system `DOWNLOAD_SERVICE`.
1331         DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1332
1333         // Parse `imageUrl`.
1334         DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1335
1336         // Get the file name from `dialogFragment`.
1337         EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1338         String imageName = downloadImageNameEditText.getText().toString();
1339
1340         // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1341         if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1342             downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1343         } else { // Only set the title using `imageName`.
1344             downloadRequest.setTitle(imageName);
1345         }
1346
1347         // Allow `MediaScanner` to index the download if it is a media file.
1348         downloadRequest.allowScanningByMediaScanner();
1349
1350         // Add the URL as the description for the download.
1351         downloadRequest.setDescription(imageUrl);
1352
1353         // Show the download notification after the download is completed.
1354         downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1355
1356         // Initiate the download.
1357         downloadManager.enqueue(downloadRequest);
1358     }
1359
1360     @Override
1361     public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1362         // Get a handle for the system `DOWNLOAD_SERVICE`.
1363         DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1364
1365         // Parse `downloadUrl`.
1366         DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1367
1368         // Get the file name from `dialogFragment`.
1369         EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1370         String fileName = downloadFileNameEditText.getText().toString();
1371
1372         // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1373         if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `fileName`.
1374             downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1375         } else { // Only set the title using `fileName`.
1376             downloadRequest.setTitle(fileName);
1377         }
1378
1379         // Allow `MediaScanner` to index the download if it is a media file.
1380         downloadRequest.allowScanningByMediaScanner();
1381
1382         // Add the URL as the description for the download.
1383         downloadRequest.setDescription(downloadUrl);
1384
1385         // Show the download notification after the download is completed.
1386         downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1387
1388         // Initiate the download.
1389         downloadManager.enqueue(downloadRequest);
1390     }
1391
1392     public void viewSslCertificate(View view) {
1393         // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1394         DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1395         viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1396     }
1397
1398     @Override
1399     public void onSslErrorCancel() {
1400         sslErrorHandler.cancel();
1401     }
1402
1403     @Override
1404     public void onSslErrorProceed() {
1405         sslErrorHandler.proceed();
1406     }
1407
1408     @Override
1409     public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1410         // Load the history entry.
1411         mainWebView.goBackOrForward(moveBackOrForwardSteps);
1412     }
1413
1414     @Override
1415     public void onClearHistory() {
1416         // Clear the history.
1417         mainWebView.clearHistory();
1418     }
1419
1420     // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1421     @Override
1422     public void onBackPressed() {
1423         // Close the navigation drawer if it is available.  GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1424         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1425             drawerLayout.closeDrawer(GravityCompat.START);
1426         } else {
1427             // Load the previous URL if available.
1428             if (mainWebView.canGoBack()) {
1429                 mainWebView.goBack();
1430             } else {
1431                 // Pass `onBackPressed()` to the system.
1432                 super.onBackPressed();
1433             }
1434         }
1435     }
1436
1437     @Override
1438     public void onPause() {
1439         // Pause `mainWebView`.
1440         mainWebView.onPause();
1441
1442         // Stop all JavaScript.
1443         mainWebView.pauseTimers();
1444
1445         // Pause the adView or it will continue to consume resources in the background on the free flavor.
1446         if (BuildConfig.FLAVOR.contentEquals("free")) {
1447             BannerAd.pauseAd(adView);
1448         }
1449
1450         super.onPause();
1451     }
1452
1453     @Override
1454     public void onResume() {
1455         super.onResume();
1456
1457         // Resume JavaScript (if enabled).
1458         mainWebView.resumeTimers();
1459
1460         // Resume `mainWebView`.
1461         mainWebView.onResume();
1462
1463         // Resume the adView for the free flavor.
1464         if (BuildConfig.FLAVOR.contentEquals("free")) {
1465             BannerAd.resumeAd(adView);
1466         }
1467     }
1468
1469     @Override
1470     public void onRestart() {
1471         super.onRestart();
1472
1473         // Apply the settings from shared preferences, which might have been changed in `Settings`.
1474         applySettings();
1475
1476         // Update the privacy icon.  `true` runs `invalidateOptionsMenu` as the last step.
1477         updatePrivacyIcons(true);
1478
1479     }
1480
1481     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1482         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
1483         String unformattedUrlString = urlTextBox.getText().toString().trim();
1484
1485         URL unformattedUrl = null;
1486         Uri.Builder formattedUri = new Uri.Builder();
1487
1488         // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
1489         if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1490             // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
1491             if (!unformattedUrlString.startsWith("http")) {
1492                 unformattedUrlString = "http://" + unformattedUrlString;
1493             }
1494
1495             // 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.
1496             try {
1497                 unformattedUrl = new URL(unformattedUrlString);
1498             } catch (MalformedURLException e) {
1499                 e.printStackTrace();
1500             }
1501
1502             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1503             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1504             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1505             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1506             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1507             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1508
1509             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1510             formattedUrlString = formattedUri.build().toString();
1511         } else {
1512             // Sanitize the search input and convert it to a DuckDuckGo search.
1513             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1514
1515             // Use the correct search URL.
1516             if (javaScriptEnabled) {  // JavaScript is enabled.
1517                 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1518             } else { // JavaScript is disabled.
1519                 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1520             }
1521         }
1522
1523         mainWebView.loadUrl(formattedUrlString, customHeaders);
1524
1525         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
1526         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1527     }
1528
1529     public void findPreviousOnPage(View view) {
1530         // Go to the previous highlighted phrase on the page.  `false` goes backwards instead of forwards.
1531         mainWebView.findNext(false);
1532     }
1533
1534     public void findNextOnPage(View view) {
1535         // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
1536         mainWebView.findNext(true);
1537     }
1538
1539     public void closeFindOnPage(View view) {
1540         // Delete the contents of `find_on_page_edittext`.
1541         findOnPageEditText.setText(null);
1542
1543         // Clear the highlighted phrases.
1544         mainWebView.clearMatches();
1545
1546         // Hide the Find on Page `RelativeLayout`.
1547         LinearLayout findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
1548         findOnPageLinearLayout.setVisibility(View.GONE);
1549
1550         // Show the URL app bar.
1551         Toolbar appBarToolbar = (Toolbar) findViewById(R.id.app_bar);
1552         appBarToolbar.setVisibility(View.VISIBLE);
1553
1554         // Hide the keyboard so we can see the webpage.  `0` indicates no additional flags.
1555         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1556     }
1557
1558     private void applySettings() {
1559         // Get the shared preference values.  `this` references the current context.
1560         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1561
1562         // Store the values from `sharedPreferences` in variables.
1563         String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
1564         String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1565         String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1566         String javaScriptDisabledCustomSearchString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1567         String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1568         String javaScriptEnabledCustomSearchString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1569         String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1570         String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1571         swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1572         boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", true);
1573         boolean proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1574         hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
1575         translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
1576
1577         // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1578         if (javaScriptEnabled == null) {  // If `javaScriptEnabled` is null the program is just starting.
1579             // Get the values from `sharedPreferences`.
1580             javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1581             firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1582             thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1583             domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1584             saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1585
1586             // Apply the default settings.
1587             mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1588             cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1589             mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1590             mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1591             mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1592
1593             // Set third-party cookies status if API >= 21.
1594             if (Build.VERSION.SDK_INT >= 21) {
1595                 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1596             }
1597         }
1598
1599         // Apply the other settings from `sharedPreferences`.
1600         homepage = homepageString;
1601         swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1602
1603         // Set the user agent initial status.
1604         switch (userAgentString) {
1605             case "Default user agent":
1606                 // Set the user agent to `""`, which uses the default value.
1607                 mainWebView.getSettings().setUserAgentString("");
1608                 break;
1609
1610             case "Custom user agent":
1611                 // Set the custom user agent.
1612                 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1613                 break;
1614
1615             default:
1616                 // Use the selected user agent.
1617                 mainWebView.getSettings().setUserAgentString(userAgentString);
1618                 break;
1619         }
1620
1621         // Set JavaScript disabled search.
1622         if (javaScriptDisabledSearchString.equals("Custom URL")) {  // Get the custom URL string.
1623             javaScriptDisabledSearchURL = javaScriptDisabledCustomSearchString;
1624         } else {  // Use the string from the pre-built list.
1625             javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1626         }
1627
1628         // Set JavaScript enabled search.
1629         if (javaScriptEnabledSearchString.equals("Custom URL")) {  // Get the custom URL string.
1630             javaScriptEnabledSearchURL = javaScriptEnabledCustomSearchString;
1631         } else {  // Use the string from the pre-built list.
1632             javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1633         }
1634
1635         // Set Do Not Track status.
1636         if (doNotTrackEnabled) {
1637             customHeaders.put("DNT", "1");
1638         } else {
1639             customHeaders.remove("DNT");
1640         }
1641
1642         // Set Orbot proxy status.
1643         if (proxyThroughOrbot) {
1644             // Set the proxy.  `this` refers to the current activity where an `AlertDialog` might be displayed.
1645             OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1646         } else {  // Reset the proxy to default.  The host is `""` and the port is `"0"`.
1647             OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1648         }
1649
1650         // If we are in full screen mode update the `SYSTEM_UI` flags.
1651         if (!appBar.isShowing()) {
1652             if (hideSystemBarsOnFullscreen) {  // Hide everything.
1653                 // Remove the translucent navigation setting if it is currently flagged.
1654                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1655
1656                 // Remove the translucent status bar overlay.
1657                 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1658
1659                 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1660                 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1661
1662                 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1663                  * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1664                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1665                  */
1666                 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1667             } else {  // Hide everything except the status and navigation bars.
1668                 // Add the translucent status flag if it is unset.
1669                 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1670
1671                 if (translucentNavigationBarOnFullscreen) {
1672                     // Set the navigation bar to be translucent.
1673                     getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1674                 } else {
1675                     // Set the navigation bar to be black.
1676                     getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1677                 }
1678             }
1679         }
1680     }
1681
1682     private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
1683         // Get handles for the icons.
1684         MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1685         MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1686         MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1687         MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1688
1689         // Update `privacyIcon`.
1690         if (javaScriptEnabled) {  // JavaScript is enabled.
1691             privacyIcon.setIcon(R.drawable.javascript_enabled);
1692         } else if (firstPartyCookiesEnabled) {  // JavaScript is disabled but cookies are enabled.
1693             privacyIcon.setIcon(R.drawable.warning);
1694         } else {  // All the dangerous features are disabled.
1695             privacyIcon.setIcon(R.drawable.privacy_mode);
1696         }
1697
1698         // Update `firstPartyCookiesIcon`.
1699         if (firstPartyCookiesEnabled) {  // First-party cookies are enabled.
1700             firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1701         } else {  // First-party cookies are disabled.
1702             firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1703         }
1704
1705         // Update `domStorageIcon`.
1706         if (javaScriptEnabled && domStorageEnabled) {  // Both JavaScript and DOM storage are enabled.
1707             domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1708         } else if (javaScriptEnabled) {  // JavaScript is enabled but DOM storage is disabled.
1709             domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
1710         } else {  // JavaScript is disabled, so DOM storage is ghosted.
1711             domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
1712         }
1713
1714         // Update `formDataIcon`.
1715         if (saveFormDataEnabled) {  // Form data is enabled.
1716             formDataIcon.setIcon(R.drawable.form_data_enabled);
1717         } else {  // Form data is disabled.
1718             formDataIcon.setIcon(R.drawable.form_data_disabled);
1719         }
1720
1721         // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`.  `this` references the current activity.
1722         if (runInvalidateOptionsMenu) {
1723             ActivityCompat.invalidateOptionsMenu(this);
1724         }
1725     }
1726 }