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