]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/MainWebViewActivity.java
Create controls for font size.
[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 the homepage initial status.  The default value is `https://www.duckduckgo.com`.
419         homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
420
421         // Set the font size initial status.  the default value is `100`.
422         String defaultFontSizeString = savedPreferences.getString("default_font_size", "100");
423         mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
424
425         // Set the swipe to refresh initial status.  The default is `true`.
426         swipeToRefreshEnabled = savedPreferences.getBoolean("swipe_to_refresh_enabled", true);
427         swipeToRefresh.setEnabled(swipeToRefreshEnabled);
428
429
430         // Get the intent information that started the app.
431         final Intent intent = getIntent();
432
433         if (intent.getData() != null) {
434             // Get the intent data and convert it to a string.
435             final Uri intentUriData = intent.getData();
436             formattedUrlString = intentUriData.toString();
437         }
438
439         // If formattedUrlString is null assign the homepage to it.
440         if (formattedUrlString == null) {
441             formattedUrlString = homepage;
442         }
443
444         // Load the initial website.
445         mainWebView.loadUrl(formattedUrlString, customHeaders);
446
447         // If the favorite icon is null, load the default.
448         if (favoriteIcon == null) {
449             // We have to use `ContextCompat` until API >= 21.
450             Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
451             BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
452             favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
453         }
454
455         // Initialize AdView for the free flavor and request an ad.  If this is not the free flavor BannerAd.requestAd() does nothing.
456         adView = findViewById(R.id.adView);
457         BannerAd.requestAd(adView);
458     }
459
460
461     @Override
462     protected void onNewIntent(Intent intent) {
463         // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
464         setIntent(intent);
465
466         if (intent.getData() != null) {
467             // Get the intent data and convert it to a string.
468             final Uri intentUriData = intent.getData();
469             formattedUrlString = intentUriData.toString();
470         }
471
472         // Close the navigation drawer if it is open.
473         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
474             drawerLayout.closeDrawer(GravityCompat.START);
475         }
476
477         // Load the website.
478         mainWebView.loadUrl(formattedUrlString, customHeaders);
479
480         // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
481         mainWebView.requestFocus();
482     }
483
484     @Override
485     public boolean onCreateOptionsMenu(Menu menu) {
486         // Inflate the menu; this adds items to the action bar if it is present.
487         getMenuInflater().inflate(R.menu.webview_options_menu, menu);
488
489         // Set mainMenu so it can be used by onOptionsItemSelected.
490         mainMenu = menu;
491
492         // Initialize privacyIcon
493         privacyIcon = menu.findItem(R.id.toggleJavaScript);
494
495         // Set the initial status of the privacy icon.
496         updatePrivacyIcon();
497
498         // Get MenuItems for checkable menu items.
499         MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
500         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
501         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
502         MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
503
504         // Set the initial status of the menu item checkboxes.
505         toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
506         toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
507         toggleDomStorage.setChecked(domStorageEnabled);
508         toggleSaveFormData.setChecked(saveFormDataEnabled);
509
510         return true;
511     }
512
513     @Override
514     public boolean onPrepareOptionsMenu(Menu menu) {
515         // Only enable Third-Party Cookies if SDK >= 21 and First-Party Cookies are enabled.
516         MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
517         if ((Build.VERSION.SDK_INT >= 21) && firstPartyCookiesEnabled) {
518             toggleThirdPartyCookies.setEnabled(true);
519         } else {
520             toggleThirdPartyCookies.setEnabled(false);
521         }
522
523         // Enable DOM Storage if JavaScript is enabled.
524         MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
525         toggleDomStorage.setEnabled(javaScriptEnabled);
526
527         // Enable Clear Cookies if there are any.
528         MenuItem clearCookies = menu.findItem(R.id.clearCookies);
529         clearCookies.setEnabled(cookieManager.hasCookies());
530
531         // Enable Clear Form Data is there is any.
532         MenuItem clearFormData = menu.findItem(R.id.clearFormData);
533         WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
534         clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
535
536         // Select the current font size.
537         int fontSize = mainWebView.getSettings().getTextZoom();
538         MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
539         MenuItem selectedFontSizeMenuItem;
540         switch (fontSize) {
541             case 50:
542                 fontSizeMenuItem.setTitle(R.string.font_size_fifty_percent);
543                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
544                 break;
545
546             case 75:
547                 fontSizeMenuItem.setTitle(R.string.font_size_seventy_five_percent);
548                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
549                 break;
550
551             case 100:
552                 fontSizeMenuItem.setTitle(R.string.font_size_one_hundred_percent);
553                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
554                 break;
555
556             case 125:
557                 fontSizeMenuItem.setTitle(R.string.font_size_one_hundred_twenty_five_percent);
558                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
559                 break;
560
561             case 150:
562                 fontSizeMenuItem.setTitle(R.string.font_size_one_hundred_fifty_percent);
563                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
564                 break;
565
566             case 175:
567                 fontSizeMenuItem.setTitle(R.string.font_size_one_hundred_seventy_five_percent);
568                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
569                 break;
570
571             case 200:
572                 fontSizeMenuItem.setTitle(R.string.font_size_two_hundred_percent);
573                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
574                 break;
575
576             default:
577                 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
578                 break;
579         }
580         selectedFontSizeMenuItem.setChecked(true);
581
582         // Only show `Refresh` if `swipeToRefresh` is disabled.
583         MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
584         refreshMenuItem.setVisible(!swipeToRefreshEnabled);
585
586         // Run all the other default commands.
587         super.onPrepareOptionsMenu(menu);
588
589         // `return true` displays the menu.
590         return true;
591     }
592
593     @Override
594     // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
595     @SuppressLint("SetJavaScriptEnabled")
596     // removeAllCookies is deprecated, but it is required for API < 21.
597     @SuppressWarnings("deprecation")
598     public boolean onOptionsItemSelected(MenuItem menuItem) {
599         int menuItemId = menuItem.getItemId();
600
601         // Set the commands that relate to the menu entries.
602         switch (menuItemId) {
603             case R.id.toggleJavaScript:
604                 // Switch the status of javaScriptEnabled.
605                 javaScriptEnabled = !javaScriptEnabled;
606
607                 // Apply the new JavaScript status.
608                 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
609
610                 // Update the privacy icon.
611                 updatePrivacyIcon();
612
613                 // Display a Snackbar.
614                 if (javaScriptEnabled) {
615                     Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
616                 } else {
617                     if (firstPartyCookiesEnabled) {
618                         Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
619                     } else {
620                         Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
621                     }
622                 }
623
624                 // Reload the WebView.
625                 mainWebView.reload();
626                 return true;
627
628             case R.id.toggleFirstPartyCookies:
629                 // Switch the status of firstPartyCookiesEnabled.
630                 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
631
632                 // Update the menu checkbox.
633                 menuItem.setChecked(firstPartyCookiesEnabled);
634
635                 // Apply the new cookie status.
636                 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
637
638                 // Update the privacy icon.
639                 updatePrivacyIcon();
640
641                 // Reload the WebView.
642                 mainWebView.reload();
643                 return true;
644
645             case R.id.toggleThirdPartyCookies:
646                 if (Build.VERSION.SDK_INT >= 21) {
647                     // Switch the status of thirdPartyCookiesEnabled.
648                     thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
649
650                     // Update the menu checkbox.
651                     menuItem.setChecked(thirdPartyCookiesEnabled);
652
653                     // Apply the new cookie status.
654                     cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
655
656                     // Reload the WebView.
657                     mainWebView.reload();
658                 } // Else do nothing because SDK < 21.
659                 return true;
660
661             case R.id.toggleDomStorage:
662                 // Switch the status of domStorageEnabled.
663                 domStorageEnabled = !domStorageEnabled;
664
665                 // Update the menu checkbox.
666                 menuItem.setChecked(domStorageEnabled);
667
668                 // Apply the new DOM Storage status.
669                 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
670
671                 // Reload the WebView.
672                 mainWebView.reload();
673                 return true;
674
675             case R.id.toggleSaveFormData:
676                 // Switch the status of saveFormDataEnabled.
677                 saveFormDataEnabled = !saveFormDataEnabled;
678
679                 // Update the menu checkbox.
680                 menuItem.setChecked(saveFormDataEnabled);
681
682                 // Apply the new form data status.
683                 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
684
685                 // Reload the WebView.
686                 mainWebView.reload();
687                 return true;
688
689             case R.id.clearCookies:
690                 if (Build.VERSION.SDK_INT < 21) {
691                     cookieManager.removeAllCookie();
692                 } else {
693                     cookieManager.removeAllCookies(null);
694                 }
695                 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
696                 return true;
697
698             case R.id.clearDomStorage:
699                 WebStorage webStorage = WebStorage.getInstance();
700                 webStorage.deleteAllData();
701                 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
702                 return true;
703
704             case R.id.clearFormData:
705                 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
706                 mainWebViewDatabase.clearFormData();
707                 mainWebView.reload();
708                 return true;
709
710             case R.id.fontSizeFiftyPercent:
711                 mainWebView.getSettings().setTextZoom(50);
712                 return true;
713
714             case R.id.fontSizeSeventyFivePercent:
715                 mainWebView.getSettings().setTextZoom(75);
716                 return true;
717
718             case R.id.fontSizeOneHundredPercent:
719                 mainWebView.getSettings().setTextZoom(100);
720                 return true;
721
722             case R.id.fontSizeOneHundredTwentyFivePercent:
723                 mainWebView.getSettings().setTextZoom(125);
724                 return true;
725
726             case R.id.fontSizeOneHundredFiftyPercent:
727                 mainWebView.getSettings().setTextZoom(150);
728                 return true;
729
730             case R.id.fontSizeOneHundredSeventyFivePercent:
731                 mainWebView.getSettings().setTextZoom(175);
732                 return true;
733
734             case R.id.fontSizeTwoHundredPercent:
735                 mainWebView.getSettings().setTextZoom(200);
736                 return true;
737
738             case R.id.share:
739                 Intent shareIntent = new Intent();
740                 shareIntent.setAction(Intent.ACTION_SEND);
741                 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
742                 shareIntent.setType("text/plain");
743                 startActivity(Intent.createChooser(shareIntent, "Share URL"));
744                 return true;
745
746             case R.id.addToHomescreen:
747                 // Show the CreateHomeScreenShortcut AlertDialog and name this instance "@string/create_shortcut".
748                 DialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
749                 createHomeScreenShortcutDialogFragment.show(getFragmentManager(), getResources().getString(R.string.create_shortcut));
750
751                 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
752                 return true;
753
754             case R.id.refresh:
755                 mainWebView.reload();
756                 return true;
757
758             default:
759                 // Don't consume the event.
760                 return super.onOptionsItemSelected(menuItem);
761         }
762     }
763
764     @Override
765     // removeAllCookies is deprecated, but it is required for API < 21.
766     @SuppressWarnings("deprecation")
767     public boolean onNavigationItemSelected(MenuItem menuItem) {
768         int menuItemId = menuItem.getItemId();
769
770         switch (menuItemId) {
771             case R.id.home:
772                 mainWebView.loadUrl(homepage, customHeaders);
773                 break;
774
775             case R.id.back:
776                 if (mainWebView.canGoBack()) {
777                     mainWebView.goBack();
778                 }
779                 break;
780
781             case R.id.forward:
782                 if (mainWebView.canGoForward()) {
783                     mainWebView.goForward();
784                 }
785                 break;
786
787             case R.id.bookmarks:
788                 // Launch BookmarksActivity.
789                 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
790                 startActivity(bookmarksIntent);
791                 break;
792
793             case R.id.downloads:
794                 // Launch the system Download Manager.
795                 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
796
797                 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
798                 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
799
800                 startActivity(downloadManagerIntent);
801                 break;
802
803             case R.id.settings:
804                 // Launch `SettingsActivity`.
805                 Intent settingsIntent = new Intent(this, SettingsActivity.class);
806                 startActivity(settingsIntent);
807                 break;
808
809             case R.id.guide:
810                 // Launch `GuideActivity`.
811                 Intent guideIntent = new Intent(this, GuideActivity.class);
812                 startActivity(guideIntent);
813                 break;
814
815             case R.id.about:
816                 // Launch `AboutActivity`.
817                 Intent aboutIntent = new Intent(this, AboutActivity.class);
818                 startActivity(aboutIntent);
819                 break;
820
821             case R.id.clearAndExit:
822                 // Clear cookies.  The commands changed slightly in API 21.
823                 if (Build.VERSION.SDK_INT >= 21) {
824                     cookieManager.removeAllCookies(null);
825                 } else {
826                     cookieManager.removeAllCookie();
827                 }
828
829                 // Clear DOM storage.
830                 WebStorage domStorage = WebStorage.getInstance();
831                 domStorage.deleteAllData();
832
833                 // Clear form data.
834                 WebViewDatabase formData = WebViewDatabase.getInstance(this);
835                 formData.clearFormData();
836
837                 // Clear cache.  The argument of "true" includes disk files.
838                 mainWebView.clearCache(true);
839
840                 // Clear the back/forward history.
841                 mainWebView.clearHistory();
842
843                 formattedUrlString = null;
844
845                 // Destroy the internal state of the webview.
846                 mainWebView.destroy();
847
848                 // Close Privacy Browser.  finishAndRemoveTask also removes Privacy Browser from the recent app list.
849                 if (Build.VERSION.SDK_INT >= 21) {
850                     finishAndRemoveTask();
851                 } else {
852                     finish();
853                 }
854                 break;
855
856             default:
857                 break;
858         }
859
860         // Close the navigation drawer.
861         drawerLayout.closeDrawer(GravityCompat.START);
862         return true;
863     }
864
865     @Override
866     public void onPostCreate(Bundle savedInstanceState) {
867         super.onPostCreate(savedInstanceState);
868
869         // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
870         drawerToggle.syncState();
871     }
872
873     @Override
874     public void onConfigurationChanged(Configuration newConfig) {
875         super.onConfigurationChanged(newConfig);
876
877         // Reload the ad if this is the free flavor.
878         BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
879
880         // Reinitialize the adView variable, as the View will have been removed and re-added in the free flavor by BannerAd.reloadAfterRotate().
881         adView = findViewById(R.id.adView);
882     }
883
884     @Override
885     public void onCancelCreateHomeScreenShortcut(DialogFragment dialogFragment) {
886         // Do nothing because the user selected "Cancel".
887     }
888
889     @Override
890     public void onCreateHomeScreenShortcut(DialogFragment dialogFragment) {
891         // Get shortcutNameEditText from the alert dialog.
892         EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
893
894         // Create the bookmark shortcut based on formattedUrlString.
895         Intent bookmarkShortcut = new Intent();
896         bookmarkShortcut.setAction(Intent.ACTION_VIEW);
897         bookmarkShortcut.setData(Uri.parse(formattedUrlString));
898
899         // Place the bookmark shortcut on the home screen.
900         Intent placeBookmarkShortcut = new Intent();
901         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
902         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
903         placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
904         placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
905         sendBroadcast(placeBookmarkShortcut);
906     }
907
908     // Override onBackPressed to handle the navigation drawer and mainWebView.
909     @Override
910     public void onBackPressed() {
911         final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
912
913         // Close the navigation drawer if it is available.  GravityCompat.START is the drawer on the left on Left-to-Right layout text.
914         if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
915             drawerLayout.closeDrawer(GravityCompat.START);
916         } else {
917             // Load the previous URL if available.
918             assert mainWebView != null; //This assert removes the incorrect warning in Android Studio on the following line that mainWebView might be null.
919             if (mainWebView.canGoBack()) {
920                 mainWebView.goBack();
921             } else {
922                 // Pass onBackPressed to the system.
923                 super.onBackPressed();
924             }
925         }
926     }
927
928     @Override
929     public void onPause() {
930         // We need to pause the adView or it will continue to consume resources in the background on the free flavor.
931         BannerAd.pauseAd(adView);
932
933         super.onPause();
934     }
935
936     @Override
937     public void onResume() {
938         super.onResume();
939
940         // We need to resume the adView for the free flavor.
941         BannerAd.resumeAd(adView);
942     }
943
944     private void loadUrlFromTextBox() throws UnsupportedEncodingException {
945         // Get the text from urlTextBox and convert it to a string.  trim() removes white spaces from the beginning and end of the string.
946         String unformattedUrlString = urlTextBox.getText().toString().trim();
947
948         URL unformattedUrl = null;
949         Uri.Builder formattedUri = new Uri.Builder();
950
951         // Check to see if unformattedUrlString is a valid URL.  Otherwise, convert it into a Duck Duck Go search.
952         if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
953             // Add http:// at the beginning if it is missing.  Otherwise the app will segfault.
954             if (!unformattedUrlString.startsWith("http")) {
955                 unformattedUrlString = "http://" + unformattedUrlString;
956             }
957
958             // 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.
959             try {
960                 unformattedUrl = new URL(unformattedUrlString);
961             } catch (MalformedURLException e) {
962                 e.printStackTrace();
963             }
964
965             // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
966             final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
967             final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
968             final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
969             final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
970             final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
971
972             formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
973             formattedUrlString = formattedUri.build().toString();
974         } else {
975             // Sanitize the search input and convert it to a DuckDuckGo search.
976             final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
977
978             // Use the correct search URL based on javaScriptEnabled.
979             if (javaScriptEnabled) {
980                 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
981             } else { // JavaScript is disabled.
982                 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
983             }
984         }
985
986         mainWebView.loadUrl(formattedUrlString, customHeaders);
987
988         // Hides the keyboard so we can see the webpage.
989         InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
990         inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
991     }
992
993     private void updatePrivacyIcon() {
994         if (javaScriptEnabled) {
995             privacyIcon.setIcon(R.drawable.javascript_enabled);
996         } else {
997             if (firstPartyCookiesEnabled) {
998                 privacyIcon.setIcon(R.drawable.warning);
999             } else {
1000                 privacyIcon.setIcon(R.drawable.privacy_mode);
1001             }
1002         }
1003     }
1004 }