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