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