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