]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/MainWebViewActivity.java
Make basic progress with the `X-Requested-With` header.
[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.Activity;
24 import android.app.DialogFragment;
25 import android.app.DownloadManager;
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.os.Build;
34 import android.os.Bundle;
35 import android.preference.PreferenceManager;
36 import android.support.design.widget.NavigationView;
37 import android.support.design.widget.Snackbar;
38 import android.support.v4.content.ContextCompat;
39 import android.support.v4.view.GravityCompat;
40 import android.support.v4.widget.DrawerLayout;
41 import android.support.v4.widget.SwipeRefreshLayout;
42 import android.support.v7.app.ActionBar;
43 import android.support.v7.app.ActionBarDrawerToggle;
44 import android.support.v7.app.AppCompatActivity;
45 import android.support.v7.widget.Toolbar;
46 import android.util.Patterns;
47 import android.view.KeyEvent;
48 import android.view.Menu;
49 import android.view.MenuItem;
50 import android.view.View;
51 import android.view.inputmethod.InputMethodManager;
52 import android.webkit.CookieManager;
53 import android.webkit.DownloadListener;
54 import android.webkit.WebChromeClient;
55 import android.webkit.WebStorage;
56 import android.webkit.WebView;
57 import android.webkit.WebViewClient;
58 import android.webkit.WebViewDatabase;
59 import android.widget.EditText;
60 import android.widget.FrameLayout;
61 import android.widget.ImageView;
62 import android.widget.ProgressBar;
63
64 import java.io.UnsupportedEncodingException;
65 import java.net.MalformedURLException;
66 import java.net.URL;
67 import java.net.URLEncoder;
68 import java.util.HashMap;
69 import java.util.Map;
70
71 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
72 public class MainWebViewActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener {
73     // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `BookmarksActivity`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
74     // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
75     public static Bitmap favoriteIcon;
76
77     // `mainWebView` is public static so it can be accessed from `SettingsFragment`.
78     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, and `loadUrlFromTextBox()`.
79     public static WebView mainWebView;
80
81     // `formattedUrlString` is public static so it can be accessed from `BookmarksActivity`.
82     // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
83     public static String formattedUrlString;
84
85     // `mainMenu` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreateOptionsMenu()` and `onOptionsItemSelected()`.
86     public static Menu mainMenu;
87
88     // `cookieManager` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`.
89     public static CookieManager cookieManager;
90
91     // `javaScriptEnabled` is public static so it can be accessed from `SettingsFragment`.
92     // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
93     public static boolean javaScriptEnabled;
94
95     // `firstPartyCookiesEnabled` is public static so it can be accessed from `SettingsFragment`.
96     // It is also used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
97     public static boolean firstPartyCookiesEnabled;
98
99     // `thirdPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
100     public static boolean thirdPartyCookiesEnabled;
101
102     // `domStorageEnabled` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`.
103     public static boolean domStorageEnabled;
104
105     // `saveFormDataEnabled` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()`, `onCreateOptionsMenu()`, and `onOptionsItemSelected()`.
106     public static boolean saveFormDataEnabled;
107
108     // `javaScriptDisabledSearchURL` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()` and `loadURLFromTextBox()`.
109     public static String javaScriptDisabledSearchURL;
110
111     // `javaScriptEnabledSearchURL` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()` and `loadURLFromTextBox()`.
112     public static String javaScriptEnabledSearchURL;
113
114     // `homepage` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()` and `onOptionsItemSelected()`.
115     public static String homepage;
116
117     // `swipeToRefresh` is public static so it can be accessed from SettingsFragment.  It is also used in onCreate().
118     public static SwipeRefreshLayout swipeToRefresh;
119
120     // `swipeToRefreshEnabled` is public static so it can be accessed from `SettingsFragment`.  It is also used in `onCreate()`.
121     public static boolean swipeToRefreshEnabled;
122
123     // `customHeader` is public static so it can be accessed from `BookmarksActivity`.  It is also used in `onCreate()` and `loadUrlFromTextBox()`.
124     public static Map<String, String> customHeaders = new HashMap<String, String>();
125
126
127
128     // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
129     private ActionBarDrawerToggle drawerToggle;
130
131     // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
132     private DrawerLayout drawerLayout;
133
134     // `privacyIcon` is used in `onCreateOptionsMenu()` and `updatePrivacyIcon()`.
135     private MenuItem privacyIcon;
136
137     // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
138     private EditText urlTextBox;
139
140     // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
141     private View adView;
142
143     @Override
144     // 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.
145     @SuppressLint("SetJavaScriptEnabled")
146     protected void onCreate(Bundle savedInstanceState) {
147         super.onCreate(savedInstanceState);
148         setContentView(R.layout.main_coordinatorlayout);
149
150         // We need to use the SupportActionBar from android.support.v7.app.ActionBar until the minimum API is >= 21.
151         Toolbar supportAppBar = (Toolbar) findViewById(R.id.appBar);
152         setSupportActionBar(supportAppBar);
153         final ActionBar appBar = getSupportActionBar();
154
155         // This is needed to get rid of the Android Studio warning that appBar might be null.
156         assert appBar != null;
157
158         // Add the custom url_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
159         appBar.setCustomView(R.layout.url_bar);
160         appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
161
162         // Set the "go" button on the keyboard to load the URL in urlTextBox.
163         urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
164         urlTextBox.setOnKeyListener(new View.OnKeyListener() {
165             public boolean onKey(View v, int keyCode, KeyEvent event) {
166                 // If the event is a key-down event on the "enter" button, load the URL.
167                 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
168                     // Load the URL into the mainWebView and consume the event.
169                     try {
170                         loadUrlFromTextBox();
171                     } catch (UnsupportedEncodingException e) {
172                         e.printStackTrace();
173                     }
174                     // If the enter key was pressed, consume the event.
175                     return true;
176                 } else {
177                     // If any other key was pressed, do not consume the event.
178                     return false;
179                 }
180             }
181         });
182
183         final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
184
185         // Implement swipe to refresh
186         swipeToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
187         assert swipeToRefresh != null; //This assert removes the incorrect warning on the following line that swipeToRefresh might be null.
188         swipeToRefresh.setColorSchemeResources(R.color.blue);
189         swipeToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
190             @Override
191             public void onRefresh() {
192                 mainWebView.reload();
193             }
194         });
195
196         mainWebView = (WebView) findViewById(R.id.mainWebView);
197
198         // Create the navigation drawer.
199         drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
200         // The DrawerTitle identifies the drawer in accessibility mode.
201         drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
202
203         // Listen for touches on the navigation menu.
204         final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
205         assert navigationView != null; // This assert removes the incorrect warning on the following line that navigationView might be null.
206         navigationView.setNavigationItemSelectedListener(this);
207
208         // drawerToggle creates the hamburger icon at the start of the AppBar.
209         drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation, R.string.close_navigation);
210
211         // 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).
212         customHeaders.put("X-Requested-With", "");
213
214         mainWebView.setWebViewClient(new WebViewClient() {
215             // shouldOverrideUrlLoading makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
216             @Override
217             public boolean shouldOverrideUrlLoading(WebView view, String url) {
218                 // Use an external email program if the link begins with "mailto:".
219                 if (url.startsWith("mailto:")) {
220                     // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
221                     Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
222
223                     // Parse the url and set it as the data for the `Intent`.
224                     emailIntent.setData(Uri.parse(url));
225
226                     // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
227                     emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
228
229                     // Make it so.
230                     startActivity(emailIntent);
231                     return true;
232                 } else {  // Load the URL in Privacy Browser.
233                     mainWebView.loadUrl(url, customHeaders);
234                     return true;
235                 }
236             }
237
238             // Update the URL in urlTextBox when the page starts to load.
239             @Override
240             public void onPageStarted(WebView view, String url, Bitmap favicon) {
241                 urlTextBox.setText(url);
242             }
243
244             // Update formattedUrlString and urlTextBox.  It is necessary to do this after the page finishes loading because the final URL can change during load.
245             @Override
246             public void onPageFinished(WebView view, String url) {
247                 formattedUrlString = url;
248
249                 // Only update urlTextBox if the user is not typing in it.
250                 if (!urlTextBox.hasFocus()) {
251                     urlTextBox.setText(formattedUrlString);
252                 }
253             }
254         });
255
256         mainWebView.setWebChromeClient(new WebChromeClient() {
257             // Update the progress bar when a page is loading.
258             @Override
259             public void onProgressChanged(WebView view, int progress) {
260                 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
261                 progressBar.setProgress(progress);
262                 if (progress < 100) {
263                     progressBar.setVisibility(View.VISIBLE);
264                 } else {
265                     progressBar.setVisibility(View.GONE);
266
267                     //Stop the SwipeToRefresh indicator if it is running
268                     swipeToRefresh.setRefreshing(false);
269                 }
270             }
271
272             // Set the favorite icon when it changes.
273             @Override
274             public void onReceivedIcon(WebView view, Bitmap icon) {
275                 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
276                 favoriteIcon = icon;
277
278                 // Place the favorite icon in the appBar.
279                 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
280                 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
281             }
282
283             // Enter full screen video
284             @Override
285             public void onShowCustomView(View view, CustomViewCallback callback) {
286                 appBar.hide();
287
288                 // Show the fullScreenVideoFrameLayout.
289                 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
290                 fullScreenVideoFrameLayout.addView(view);
291                 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
292
293                 // Hide the mainWebView.
294                 mainWebView.setVisibility(View.GONE);
295
296                 // Hide the ad if this is the free flavor.
297                 BannerAd.hideAd(adView);
298
299                 /* SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bars on the bottom or right of the screen.
300                  * SYSTEM_UI_FLAG_FULLSCREEN hides the status bar across the top of the screen.
301                  * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the navigation and status bars ghosted overlays and automatically rehides them.
302                  */
303                 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
304             }
305
306             // Exit full screen video
307             public void onHideCustomView() {
308                 appBar.show();
309
310                 // Show the mainWebView.
311                 mainWebView.setVisibility(View.VISIBLE);
312
313                 // Show the ad if this is the free flavor.
314                 BannerAd.showAd(adView);
315
316                 // Hide the fullScreenVideoFrameLayout.
317                 assert fullScreenVideoFrameLayout != null; //This assert removes the incorrect warning on the following line that fullScreenVideoFrameLayout might be null.
318                 fullScreenVideoFrameLayout.removeAllViews();
319                 fullScreenVideoFrameLayout.setVisibility(View.GONE);
320             }
321         });
322
323         // Allow the downloading of files.
324         mainWebView.setDownloadListener(new DownloadListener() {
325             // Launch the Android download manager when a link leads to a download.
326             @Override
327             public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
328                 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
329                 DownloadManager.Request requestUri = new DownloadManager.Request(Uri.parse(url));
330
331                 // Add the URL as the description for the download.
332                 requestUri.setDescription(url);
333
334                 // Show the download notification after the download is completed.
335                 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
336
337                 // Initiate the download and display a Snackbar.
338                 downloadManager.enqueue(requestUri);
339                 Snackbar.make(findViewById(R.id.mainWebView), R.string.download_started, Snackbar.LENGTH_SHORT).show();
340             }
341         });
342
343         // Allow pinch to zoom.
344         mainWebView.getSettings().setBuiltInZoomControls(true);
345
346         // Hide zoom controls.
347         mainWebView.getSettings().setDisplayZoomControls(false);
348
349
350         // Initialize the default preference values the first time the program is run.
351         PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
352
353         // Get the shared preference values.
354         SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
355
356         // Set JavaScript initial status.  The default value is false.
357         javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
358         mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
359
360         // Initialize cookieManager.
361         cookieManager = CookieManager.getInstance();
362
363         // Set cookies initial status.  The default value is false.
364         firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false);
365         cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
366
367         // Set third-party cookies initial status if API >= 21.  The default value is false.
368         if (Build.VERSION.SDK_INT >= 21) {
369             thirdPartyCookiesEnabled = savedPreferences.getBoolean("third_party_cookies_enabled", false);
370             cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
371         }
372
373         // Set DOM storage initial status.  The default value is false.
374         domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
375         mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
376
377         // Set the saved form data initial status.  The default is false.
378         saveFormDataEnabled = savedPreferences.getBoolean("save_form_data_enabled", false);
379         mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
380
381         // Set the user agent initial status.
382         String userAgentString = savedPreferences.getString("user_agent", "Default user agent");
383         switch (userAgentString) {
384             case "Default user agent":
385                 // Do nothing.
386                 break;
387
388             case "Custom user agent":
389                 // Set the custom user agent on mainWebView,  The default is "PrivacyBrowser/1.0".
390                 mainWebView.getSettings().setUserAgentString(savedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0"));
391                 break;
392
393             default:
394                 // Set the selected user agent on mainWebView.  The default is "PrivacyBrowser/1.0".
395                 mainWebView.getSettings().setUserAgentString(savedPreferences.getString("user_agent", "PrivacyBrowser/1.0"));
396                 break;
397         }
398
399         // Set the initial string for JavaScript disabled search.
400         if (savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=").equals("Custom URL")) {
401             // Get the custom URL string.  The default is "".
402             javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search_custom_url", "");
403         } else {
404             // Use the string from javascript_disabled_search.
405             javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
406         }
407
408         // Set the initial string for JavaScript enabled search.
409         if (savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=").equals("Custom URL")) {
410             // Get the custom URL string.  The default is "".
411             javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search_custom_url", "");
412         } else {
413             // Use the string from javascript_enabled_search.
414             javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
415         }
416
417
418         // Set homepage initial status.  The default value is "https://www.duckduckgo.com".
419         homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
420
421         // Set swipe to refresh initial status.  The default is true.
422         swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
423         swipeToRefresh.setEnabled(swipeToRefreshEnabled);
424
425
426         // Get the intent information that started the app.
427         final Intent intent = getIntent();
428
429         if (intent.getData() != null) {
430             // Get the intent data and convert it to a string.
431             final Uri intentUriData = intent.getData();
432             formattedUrlString = intentUriData.toString();
433         }
434
435         // If formattedUrlString is null assign the homepage to it.
436         if (formattedUrlString == null) {
437             formattedUrlString = homepage;
438         }
439
440         // Load the initial website.
441         mainWebView.loadUrl(formattedUrlString, customHeaders);
442
443         // If the favorite icon is null, load the default.
444         if (favoriteIcon == null) {
445             // We have to use `ContextCompat` until API >= 21.
446             Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
447             BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
448             favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
449         }
450
451         // Initialize AdView for the free flavor and request an ad.  If this is not the free flavor BannerAd.requestAd() does nothing.
452         adView = findViewById(R.id.adView);
453         BannerAd.requestAd(adView);
454     }
455
456
457     @Override
458     protected void onNewIntent(Intent intent) {
459         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
460         setIntent(intent);
461
462         if (intent.getData() != null) {
463             // Get the intent data and convert it to a string.
464             final Uri intentUriData = intent.getData();
465             formattedUrlString = intentUriData.toString();
466         }
467
468         // Close the navigation drawer if it is open.
469         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
470             drawerLayout.closeDrawer(GravityCompat.START);
471         }
472
473         // Load the website.
474         mainWebView.loadUrl(formattedUrlString, customHeaders);
475
476         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
477         mainWebView.requestFocus();
478     }
479
480     @Override
481     public boolean onCreateOptionsMenu(Menu menu) {
482         // Inflate the menu; this adds items to the action bar if it is present.
483         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
484
485         // Set mainMenu so it can be used by onOptionsItemSelected.
486         mainMenu = menu;
487
488         // Initialize privacyIcon
489         privacyIcon = menu.findItem(R.id.toggleJavaScript);
490
491         // Get MenuItems for checkable menu items.
492         MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
493         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
494         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
495         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
496
497         // Set the initial status of the privacy icon.
498         updatePrivacyIcon();
499
500         // Set the initial status of the menu item checkboxes.
501         toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
502         toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
503         toggleDomStorage.setChecked(domStorageEnabled);
504         toggleSaveFormData.setChecked(saveFormDataEnabled);
505
506         return true;
507     }
508
509     @Override
510     public boolean onPrepareOptionsMenu(Menu menu) {
511         // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
512         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
513         if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
514             toggleThirdPartyCookies.setEnabled(true);
515         } else {
516             toggleThirdPartyCookies.setEnabled(false);
517         }
518
519         // Enable DOM Storage if JavaScript is enabled.
520         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
521         toggleDomStorage.setEnabled(javaScriptEnabled);
522
523         // Enable Clear Cookies if there are any.
524         MenuItem clearCookies = menu.findItem(R.id.clearCookies);
525         clearCookies.setEnabled(cookieManager.hasCookies());
526
527         // Enable Clear Form Data is there is any.
528         MenuItem clearFormData = menu.findItem(R.id.clearFormData);
529         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
530         clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
531
532         // Run all the other default commands.
533         super.onPrepareOptionsMenu(menu);
534
535         // `return true` displays the menu.
536         return true;
537     }
538
539     @Override
540     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
541     @SuppressLint("SetJavaScriptEnabled")
542     // removeAllCookies is deprecated, but it is required for API < 21.
543     @SuppressWarnings("deprecation")
544     public boolean onOptionsItemSelected(MenuItem menuItem) {
545         int menuItemId = menuItem.getItemId();
546
547         // Set the commands that relate to the menu entries.
548         switch (menuItemId) {
549             case R.id.toggleJavaScript:
550                 // Switch the status of javaScriptEnabled.
551                 javaScriptEnabled = !javaScriptEnabled;
552
553                 // Apply the new JavaScript status.
554                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
555
556                 // Update the privacy icon.
557                 updatePrivacyIcon();
558
559                 // Display a Snackbar.
560                 if (javaScriptEnabled) {
561                     Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
562                 } else {
563                     if (firstPartyCookiesEnabled) {
564                         Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
565                     } else {
566                         Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
567                     }
568                 }
569
570                 // Reload the WebView.
571                 mainWebView.reload();
572                 return true;
573
574             case R.id.toggleFirstPartyCookies:
575                 // Switch the status of firstPartyCookiesEnabled.
576                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
577
578                 // Update the menu checkbox.
579                 menuItem.setChecked(firstPartyCookiesEnabled);
580
581                 // Apply the new cookie status.
582                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
583
584                 // Update the privacy icon.
585                 updatePrivacyIcon();
586
587                 // Reload the WebView.
588                 mainWebView.reload();
589                 return true;
590
591             case R.id.toggleThirdPartyCookies:
592                 if (Build.VERSION.SDK_INT >= 21) {
593                     // Switch the status of thirdPartyCookiesEnabled.
594                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
595
596                     // Update the menu checkbox.
597                     menuItem.setChecked(thirdPartyCookiesEnabled);
598
599                     // Apply the new cookie status.
600                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
601
602                     // Reload the WebView.
603                     mainWebView.reload();
604                 } // Else do nothing because SDK < 21.
605                 return true;
606
607             case R.id.toggleDomStorage:
608                 // Switch the status of domStorageEnabled.
609                 domStorageEnabled = !domStorageEnabled;
610
611                 // Update the menu checkbox.
612                 menuItem.setChecked(domStorageEnabled);
613
614                 // Apply the new DOM Storage status.
615                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
616
617                 // Reload the WebView.
618                 mainWebView.reload();
619                 return true;
620
621             case R.id.toggleSaveFormData:
622                 // Switch the status of saveFormDataEnabled.
623                 saveFormDataEnabled = !saveFormDataEnabled;
624
625                 // Update the menu checkbox.
626                 menuItem.setChecked(saveFormDataEnabled);
627
628                 // Apply the new form data status.
629                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
630
631                 // Reload the WebView.
632                 mainWebView.reload();
633                 return true;
634
635             case R.id.clearCookies:
636                 if (Build.VERSION.SDK_INT < 21) {
637                     cookieManager.removeAllCookie();
638                 } else {
639                     cookieManager.removeAllCookies(null);
640                 }
641                 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
642                 return true;
643
644             case R.id.clearDomStorage:
645                 WebStorage webStorage = WebStorage.getInstance();
646                 webStorage.deleteAllData();
647                 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
648                 return true;
649
650             case R.id.clearFormData:
651                 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
652                 mainWebViewDatabase.clearFormData();
653                 mainWebView.reload();
654                 return true;
655
656             case R.id.share:
657                 Intent shareIntent = new Intent();
658                 shareIntent.setAction(Intent.ACTION_SEND);
659                 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
660                 shareIntent.setType("text/plain");
661                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
662                 return true;
663
664             case R.id.addToHomescreen:
665                 // Show the CreateHomeScreenShortcut AlertDialog and name this instance "@string/create_shortcut".
666                 DialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
667                 createHomeScreenShortcutDialogFragment.show(getFragmentManager(), getResources().getString(R.string.create_shortcut));
668
669                 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
670                 return true;
671
672             case R.id.refresh:
673                 mainWebView.reload();
674                 return true;
675
676             default:
677                 // Don't consume the event.
678                 return super.onOptionsItemSelected(menuItem);
679         }
680     }
681
682     @Override
683     // removeAllCookies is deprecated, but it is required for API < 21.
684     @SuppressWarnings("deprecation")
685     public boolean onNavigationItemSelected(MenuItem menuItem) {
686         int menuItemId = menuItem.getItemId();
687
688         switch (menuItemId) {
689             case R.id.home:
690                 mainWebView.loadUrl(homepage, customHeaders);
691                 break;
692
693             case R.id.back:
694                 if (mainWebView.canGoBack()) {
695                     mainWebView.goBack();
696                 }
697                 break;
698
699             case R.id.forward:
700                 if (mainWebView.canGoForward()) {
701                     mainWebView.goForward();
702                 }
703                 break;
704
705             case R.id.bookmarks:
706                 // Launch BookmarksActivity.
707                 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
708                 startActivity(bookmarksIntent);
709                 break;
710
711             case R.id.downloads:
712                 // Launch the system Download Manager.
713                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
714
715                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
716                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
717
718                 startActivity(downloadManagerIntent);
719                 break;
720
721             case R.id.settings:
722                 // Launch `SettingsActivity`.
723                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
724                 startActivity(settingsIntent);
725                 break;
726
727             case R.id.guide:
728                 // Launch `GuideActivity`.
729                 Intent guideIntent = new Intent(this, GuideActivity.class);
730                 startActivity(guideIntent);
731                 break;
732
733             case R.id.about:
734                 // Launch `AboutActivity`.
735                 Intent aboutIntent = new Intent(this, AboutActivity.class);
736                 startActivity(aboutIntent);
737                 break;
738
739             case R.id.clearAndExit:
740                 // Clear cookies.  The commands changed slightly in API 21.
741                 if (Build.VERSION.SDK_INT >= 21) {
742                     cookieManager.removeAllCookies(null);
743                 } else {
744                     cookieManager.removeAllCookie();
745                 }
746
747                 // Clear DOM storage.
748                 WebStorage domStorage = WebStorage.getInstance();
749                 domStorage.deleteAllData();
750
751                 // Clear form data.
752                 WebViewDatabase formData = WebViewDatabase.getInstance(this);
753                 formData.clearFormData();
754
755                 // Clear cache.  The argument of "true" includes disk files.
756                 mainWebView.clearCache(true);
757
758                 // Clear the back/forward history.
759                 mainWebView.clearHistory();
760
761                 formattedUrlString = null;
762
763                 // Destroy the internal state of the webview.
764                 mainWebView.destroy();
765
766                 // Close Privacy Browser.  finishAndRemoveTask also removes Privacy Browser from the recent app list.
767                 if (Build.VERSION.SDK_INT >= 21) {
768                     finishAndRemoveTask();
769                 } else {
770                     finish();
771                 }
772                 break;
773
774             default:
775                 break;
776         }
777
778         // Close the navigation drawer.
779         drawerLayout.closeDrawer(GravityCompat.START);
780         return true;
781     }
782
783     @Override
784     public void onPostCreate(Bundle savedInstanceState) {
785         super.onPostCreate(savedInstanceState);
786
787         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
788         drawerToggle.syncState();
789     }
790
791     @Override
792     public void onConfigurationChanged(Configuration newConfig) {
793         super.onConfigurationChanged(newConfig);
794
795         // Reload the ad if this is the free flavor.
796         BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
797
798         // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
799         adView = findViewById(R.id.adView);
800     }
801
802     @Override
803     public void onCancelCreateHomeScreenShortcut(DialogFragment dialogFragment) {
804         // Do nothing because the user selected "Cancel".
805     }
806
807     @Override
808     public void onCreateHomeScreenShortcut(DialogFragment dialogFragment) {
809         // Get shortcutNameEditText from the alert dialog.
810         EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
811
812         // Create the bookmark shortcut based on formattedUrlString.
813         Intent bookmarkShortcut = new Intent();
814         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
815         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
816
817         // Place the bookmark shortcut on the home screen.
818         Intent placeBookmarkShortcut = new Intent();
819         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
820         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
821         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
822         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
823         sendBroadcast(placeBookmarkShortcut);
824     }
825
826     // Override onBackPressed to handle the navigation drawer and mainWebView.
827     @Override
828     public void onBackPressed() {
829         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
830
831         // Close the navigation drawer if it is available.  GravityCompat.START is the drawer on the left on Left-to-Right layout text.
832         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
833             drawerLayout.closeDrawer(GravityCompat.START);
834         } else {
835             // Load the previous URL if available.
836             assert mainWebView != null; //This assert removes the incorrect warning in Android Studio on the following line that mainWebView might be null.
837             if (mainWebView.canGoBack()) {
838                 mainWebView.goBack();
839             } else {
840                 // Pass onBackPressed to the system.
841                 super.onBackPressed();
842             }
843         }
844     }
845
846     @Override
847     public void onPause() {
848         // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
849         BannerAd.pauseAd(adView);
850
851         super.onPause();
852     }
853
854     @Override
855     public void onResume() {
856         super.onResume();
857
858         // We need to resume the adView for the free flavor.
859         BannerAd.resumeAd(adView);
860     }
861
862     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
863         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
864         String unformattedUrlString = urlTextBox.getText().toString().trim();
865
866         URL unformattedUrl = null;
867         Uri.Builder formattedUri = new Uri.Builder();
868
869         // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
870         if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
871             // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
872             if (!unformattedUrlString.startsWith("http")) {
873                 unformattedUrlString = "http://" + unformattedUrlString;
874             }
875
876             // 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.
877             try {
878                 unformattedUrl = new URL(unformattedUrlString);
879             } catch (MalformedURLException e) {
880                 e.printStackTrace();
881             }
882
883             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
884             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
885             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
886             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
887             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
888             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
889
890             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
891             formattedUrlString = formattedUri.build().toString();
892         } else {
893             // Sanitize the search input and convert it to a DuckDuckGo search.
894             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
895
896             // Use the correct search URL based on javaScriptEnabled.
897             if (javaScriptEnabled) {
898                 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
899             } else { // JavaScript is disabled.
900                 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
901             }
902         }
903
904         mainWebView.loadUrl(formattedUrlString, customHeaders);
905
906         // Hides the keyboard so we can see the webpage.
907         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
908         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
909     }
910
911     private void updatePrivacyIcon() {
912         if (javaScriptEnabled) {
913             privacyIcon.setIcon(R.drawable.javascript_enabled);
914         } else {
915             if (firstPartyCookiesEnabled) {
916                 privacyIcon.setIcon(R.drawable.warning);
917             } else {
918                 privacyIcon.setIcon(R.drawable.privacy_mode);
919             }
920         }
921     }
922 }