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