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