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