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