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