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