2 * Copyright 2015-2016 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser;
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;
64 import java.io.UnsupportedEncodingException;
65 import java.net.MalformedURLException;
67 import java.net.URLEncoder;
68 import java.util.HashMap;
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;
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;
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;
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;
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;
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;
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;
99 // `thirdPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, and `onOptionsItemSelected()`.
100 public static boolean thirdPartyCookiesEnabled;
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;
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;
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;
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;
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;
117 // `swipeToRefresh` is public static so it can be accessed from SettingsFragment. It is also used in onCreate().
118 public static SwipeRefreshLayout swipeToRefresh;
120 // `swipeToRefreshEnabled` is public static so it can be accessed from `SettingsFragment`. It is also used in `onCreate()`.
121 public static boolean swipeToRefreshEnabled;
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>();
128 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
129 private ActionBarDrawerToggle drawerToggle;
131 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
132 private DrawerLayout drawerLayout;
134 // `privacyIcon` is used in `onCreateOptionsMenu()` and `updatePrivacyIcon()`.
135 private MenuItem privacyIcon;
137 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
138 private EditText urlTextBox;
140 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
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);
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();
155 // This is needed to get rid of the Android Studio warning that appBar might be null.
156 assert appBar != null;
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);
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.
170 loadUrlFromTextBox();
171 } catch (UnsupportedEncodingException e) {
174 // If the enter key was pressed, consume the event.
177 // If any other key was pressed, do not consume the event.
183 final FrameLayout fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.fullScreenVideoFrameLayout);
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() {
191 public void onRefresh() {
192 mainWebView.reload();
196 mainWebView = (WebView) findViewById(R.id.mainWebView);
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));
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);
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);
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", "");
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.
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);
223 // Parse the url and set it as the data for the `Intent`.
224 emailIntent.setData(Uri.parse(url));
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);
230 startActivity(emailIntent);
232 } else { // Load the URL in Privacy Browser.
233 mainWebView.loadUrl(url, customHeaders);
238 // Update the URL in urlTextBox when the page starts to load.
240 public void onPageStarted(WebView view, String url, Bitmap favicon) {
241 urlTextBox.setText(url);
244 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
246 public void onPageFinished(WebView view, String url) {
247 formattedUrlString = url;
249 // Only update urlTextBox if the user is not typing in it.
250 if (!urlTextBox.hasFocus()) {
251 urlTextBox.setText(formattedUrlString);
256 mainWebView.setWebChromeClient(new WebChromeClient() {
257 // Update the progress bar when a page is loading.
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);
265 progressBar.setVisibility(View.GONE);
267 //Stop the SwipeToRefresh indicator if it is running
268 swipeToRefresh.setRefreshing(false);
272 // Set the favorite icon when it changes.
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.
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));
283 // Enter full screen video
285 public void onShowCustomView(View view, CustomViewCallback callback) {
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);
293 // Hide the mainWebView.
294 mainWebView.setVisibility(View.GONE);
296 // Hide the ad if this is the free flavor.
297 BannerAd.hideAd(adView);
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.
303 view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
306 // Exit full screen video
307 public void onHideCustomView() {
310 // Show the mainWebView.
311 mainWebView.setVisibility(View.VISIBLE);
313 // Show the ad if this is the free flavor.
314 BannerAd.showAd(adView);
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);
323 // Allow the downloading of files.
324 mainWebView.setDownloadListener(new DownloadListener() {
325 // Launch the Android download manager when a link leads to a download.
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));
331 // Add the URL as the description for the download.
332 requestUri.setDescription(url);
334 // Show the download notification after the download is completed.
335 requestUri.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
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();
343 // Allow pinch to zoom.
344 mainWebView.getSettings().setBuiltInZoomControls(true);
346 // Hide zoom controls.
347 mainWebView.getSettings().setDisplayZoomControls(false);
350 // Initialize the default preference values the first time the program is run.
351 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
353 // Get the shared preference values.
354 SharedPreferences savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
356 // Set JavaScript initial status. The default value is false.
357 javaScriptEnabled = savedPreferences.getBoolean("javascript_enabled", false);
358 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
360 // Initialize cookieManager.
361 cookieManager = CookieManager.getInstance();
363 // Set cookies initial status. The default value is false.
364 firstPartyCookiesEnabled = savedPreferences.getBoolean("first_party_cookies_enabled", false);
365 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
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);
373 // Set DOM storage initial status. The default value is false.
374 domStorageEnabled = savedPreferences.getBoolean("dom_storage_enabled", false);
375 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
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);
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":
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"));
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"));
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", "");
404 // Use the string from javascript_disabled_search.
405 javaScriptDisabledSearchURL = savedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
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", "");
413 // Use the string from javascript_enabled_search.
414 javaScriptEnabledSearchURL = savedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
418 // Set the homepage initial status. The default value is `https://www.duckduckgo.com`.
419 homepage = savedPreferences.getString("homepage", "https://www.duckduckgo.com");
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));
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);
430 // Get the intent information that started the app.
431 final Intent intent = getIntent();
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();
439 // If formattedUrlString is null assign the homepage to it.
440 if (formattedUrlString == null) {
441 formattedUrlString = homepage;
444 // Load the initial website.
445 mainWebView.loadUrl(formattedUrlString, customHeaders);
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();
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);
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.
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();
472 // Close the navigation drawer if it is open.
473 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
474 drawerLayout.closeDrawer(GravityCompat.START);
478 mainWebView.loadUrl(formattedUrlString, customHeaders);
480 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
481 mainWebView.requestFocus();
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);
489 // Set mainMenu so it can be used by onOptionsItemSelected.
492 // Initialize privacyIcon
493 privacyIcon = menu.findItem(R.id.toggleJavaScript);
495 // Set the initial status of the privacy icon.
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);
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);
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);
520 toggleThirdPartyCookies.setEnabled(false);
523 // Enable DOM Storage if JavaScript is enabled.
524 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
525 toggleDomStorage.setEnabled(javaScriptEnabled);
527 // Enable Clear Cookies if there are any.
528 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
529 clearCookies.setEnabled(cookieManager.hasCookies());
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());
536 // Select the current font size.
537 int fontSize = mainWebView.getSettings().getTextZoom();
538 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
539 MenuItem selectedFontSizeMenuItem;
542 fontSizeMenuItem.setTitle(R.string.font_size_fifty_percent);
543 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
547 fontSizeMenuItem.setTitle(R.string.font_size_seventy_five_percent);
548 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
552 fontSizeMenuItem.setTitle(R.string.font_size_one_hundred_percent);
553 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
557 fontSizeMenuItem.setTitle(R.string.font_size_one_hundred_twenty_five_percent);
558 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
562 fontSizeMenuItem.setTitle(R.string.font_size_one_hundred_fifty_percent);
563 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
567 fontSizeMenuItem.setTitle(R.string.font_size_one_hundred_seventy_five_percent);
568 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
572 fontSizeMenuItem.setTitle(R.string.font_size_two_hundred_percent);
573 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
577 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
580 selectedFontSizeMenuItem.setChecked(true);
582 // Only show `Refresh` if `swipeToRefresh` is disabled.
583 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
584 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
586 // Run all the other default commands.
587 super.onPrepareOptionsMenu(menu);
589 // `return true` displays the menu.
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();
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;
607 // Apply the new JavaScript status.
608 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
610 // Update the privacy icon.
613 // Display a Snackbar.
614 if (javaScriptEnabled) {
615 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
617 if (firstPartyCookiesEnabled) {
618 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
620 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
624 // Reload the WebView.
625 mainWebView.reload();
628 case R.id.toggleFirstPartyCookies:
629 // Switch the status of firstPartyCookiesEnabled.
630 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
632 // Update the menu checkbox.
633 menuItem.setChecked(firstPartyCookiesEnabled);
635 // Apply the new cookie status.
636 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
638 // Update the privacy icon.
641 // Reload the WebView.
642 mainWebView.reload();
645 case R.id.toggleThirdPartyCookies:
646 if (Build.VERSION.SDK_INT >= 21) {
647 // Switch the status of thirdPartyCookiesEnabled.
648 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
650 // Update the menu checkbox.
651 menuItem.setChecked(thirdPartyCookiesEnabled);
653 // Apply the new cookie status.
654 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
656 // Reload the WebView.
657 mainWebView.reload();
658 } // Else do nothing because SDK < 21.
661 case R.id.toggleDomStorage:
662 // Switch the status of domStorageEnabled.
663 domStorageEnabled = !domStorageEnabled;
665 // Update the menu checkbox.
666 menuItem.setChecked(domStorageEnabled);
668 // Apply the new DOM Storage status.
669 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
671 // Reload the WebView.
672 mainWebView.reload();
675 case R.id.toggleSaveFormData:
676 // Switch the status of saveFormDataEnabled.
677 saveFormDataEnabled = !saveFormDataEnabled;
679 // Update the menu checkbox.
680 menuItem.setChecked(saveFormDataEnabled);
682 // Apply the new form data status.
683 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
685 // Reload the WebView.
686 mainWebView.reload();
689 case R.id.clearCookies:
690 if (Build.VERSION.SDK_INT < 21) {
691 cookieManager.removeAllCookie();
693 cookieManager.removeAllCookies(null);
695 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
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();
704 case R.id.clearFormData:
705 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
706 mainWebViewDatabase.clearFormData();
707 mainWebView.reload();
710 case R.id.fontSizeFiftyPercent:
711 mainWebView.getSettings().setTextZoom(50);
714 case R.id.fontSizeSeventyFivePercent:
715 mainWebView.getSettings().setTextZoom(75);
718 case R.id.fontSizeOneHundredPercent:
719 mainWebView.getSettings().setTextZoom(100);
722 case R.id.fontSizeOneHundredTwentyFivePercent:
723 mainWebView.getSettings().setTextZoom(125);
726 case R.id.fontSizeOneHundredFiftyPercent:
727 mainWebView.getSettings().setTextZoom(150);
730 case R.id.fontSizeOneHundredSeventyFivePercent:
731 mainWebView.getSettings().setTextZoom(175);
734 case R.id.fontSizeTwoHundredPercent:
735 mainWebView.getSettings().setTextZoom(200);
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"));
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));
751 //Everything else will be handled by CreateHomeScreenShortcut and the associated listeners below.
755 mainWebView.reload();
759 // Don't consume the event.
760 return super.onOptionsItemSelected(menuItem);
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();
770 switch (menuItemId) {
772 mainWebView.loadUrl(homepage, customHeaders);
776 if (mainWebView.canGoBack()) {
777 mainWebView.goBack();
782 if (mainWebView.canGoForward()) {
783 mainWebView.goForward();
788 // Launch BookmarksActivity.
789 Intent bookmarksIntent = new Intent(this, BookmarksActivity.class);
790 startActivity(bookmarksIntent);
794 // Launch the system Download Manager.
795 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
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);
800 startActivity(downloadManagerIntent);
804 // Launch `SettingsActivity`.
805 Intent settingsIntent = new Intent(this, SettingsActivity.class);
806 startActivity(settingsIntent);
810 // Launch `GuideActivity`.
811 Intent guideIntent = new Intent(this, GuideActivity.class);
812 startActivity(guideIntent);
816 // Launch `AboutActivity`.
817 Intent aboutIntent = new Intent(this, AboutActivity.class);
818 startActivity(aboutIntent);
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);
826 cookieManager.removeAllCookie();
829 // Clear DOM storage.
830 WebStorage domStorage = WebStorage.getInstance();
831 domStorage.deleteAllData();
834 WebViewDatabase formData = WebViewDatabase.getInstance(this);
835 formData.clearFormData();
837 // Clear cache. The argument of "true" includes disk files.
838 mainWebView.clearCache(true);
840 // Clear the back/forward history.
841 mainWebView.clearHistory();
843 formattedUrlString = null;
845 // Destroy the internal state of the webview.
846 mainWebView.destroy();
848 // Close Privacy Browser. finishAndRemoveTask also removes Privacy Browser from the recent app list.
849 if (Build.VERSION.SDK_INT >= 21) {
850 finishAndRemoveTask();
860 // Close the navigation drawer.
861 drawerLayout.closeDrawer(GravityCompat.START);
866 public void onPostCreate(Bundle savedInstanceState) {
867 super.onPostCreate(savedInstanceState);
869 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
870 drawerToggle.syncState();
874 public void onConfigurationChanged(Configuration newConfig) {
875 super.onConfigurationChanged(newConfig);
877 // Reload the ad if this is the free flavor.
878 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
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);
885 public void onCancelCreateHomeScreenShortcut(DialogFragment dialogFragment) {
886 // Do nothing because the user selected "Cancel".
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);
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));
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);
908 // Override onBackPressed to handle the navigation drawer and mainWebView.
910 public void onBackPressed() {
911 final WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
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);
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();
922 // Pass onBackPressed to the system.
923 super.onBackPressed();
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);
937 public void onResume() {
940 // We need to resume the adView for the free flavor.
941 BannerAd.resumeAd(adView);
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();
948 URL unformattedUrl = null;
949 Uri.Builder formattedUri = new Uri.Builder();
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;
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.
960 unformattedUrl = new URL(unformattedUrlString);
961 } catch (MalformedURLException e) {
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;
972 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
973 formattedUrlString = formattedUri.build().toString();
975 // Sanitize the search input and convert it to a DuckDuckGo search.
976 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
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;
986 mainWebView.loadUrl(formattedUrlString, customHeaders);
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);
993 private void updatePrivacyIcon() {
994 if (javaScriptEnabled) {
995 privacyIcon.setIcon(R.drawable.javascript_enabled);
997 if (firstPartyCookiesEnabled) {
998 privacyIcon.setIcon(R.drawable.warning);
1000 privacyIcon.setIcon(R.drawable.privacy_mode);