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