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