2 * Copyright 2015-2017 Soren Stoutner <soren@stoutner.com>.
4 * Download cookie code contributed 2017 Hendrik Knackstedt. Copyright assigned to Soren Stoutner <soren@stoutner.com>.
6 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
8 * Privacy Browser is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Privacy Browser is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Privacy Browser. If not, see <http://www.gnu.org/licenses/>.
22 package com.stoutner.privacybrowser.activities;
24 import android.annotation.SuppressLint;
25 import android.app.DialogFragment;
26 import android.app.DownloadManager;
27 import android.content.BroadcastReceiver;
28 import android.content.ClipData;
29 import android.content.ClipboardManager;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.SharedPreferences;
34 import android.content.res.Configuration;
35 import android.graphics.Bitmap;
36 import android.graphics.drawable.BitmapDrawable;
37 import android.graphics.drawable.Drawable;
38 import android.net.Uri;
39 import android.net.http.SslCertificate;
40 import android.net.http.SslError;
41 import android.os.Build;
42 import android.os.Bundle;
43 import android.preference.PreferenceManager;
44 import android.print.PrintDocumentAdapter;
45 import android.print.PrintManager;
46 import android.support.annotation.NonNull;
47 import android.support.design.widget.CoordinatorLayout;
48 import android.support.design.widget.NavigationView;
49 import android.support.design.widget.Snackbar;
50 import android.support.v4.app.ActivityCompat;
51 import android.support.v4.content.ContextCompat;
52 import android.support.v4.view.GravityCompat;
53 import android.support.v4.widget.DrawerLayout;
54 import android.support.v4.widget.SwipeRefreshLayout;
55 import android.support.v7.app.ActionBar;
56 import android.support.v7.app.ActionBarDrawerToggle;
57 import android.support.v7.app.AppCompatActivity;
58 import android.support.v7.app.AppCompatDialogFragment;
59 import android.support.v7.widget.Toolbar;
60 import android.text.Editable;
61 import android.text.TextWatcher;
62 import android.util.Patterns;
63 import android.view.ContextMenu;
64 import android.view.GestureDetector;
65 import android.view.KeyEvent;
66 import android.view.Menu;
67 import android.view.MenuItem;
68 import android.view.MotionEvent;
69 import android.view.View;
70 import android.view.WindowManager;
71 import android.view.inputmethod.InputMethodManager;
72 import android.webkit.CookieManager;
73 import android.webkit.DownloadListener;
74 import android.webkit.SslErrorHandler;
75 import android.webkit.WebBackForwardList;
76 import android.webkit.WebChromeClient;
77 import android.webkit.WebResourceResponse;
78 import android.webkit.WebStorage;
79 import android.webkit.WebView;
80 import android.webkit.WebViewClient;
81 import android.webkit.WebViewDatabase;
82 import android.widget.EditText;
83 import android.widget.FrameLayout;
84 import android.widget.ImageView;
85 import android.widget.LinearLayout;
86 import android.widget.ProgressBar;
87 import android.widget.RelativeLayout;
88 import android.widget.TextView;
90 import com.stoutner.privacybrowser.BannerAd;
91 import com.stoutner.privacybrowser.BuildConfig;
92 import com.stoutner.privacybrowser.R;
93 import com.stoutner.privacybrowser.helpers.OrbotProxyHelper;
94 import com.stoutner.privacybrowser.dialogs.CreateHomeScreenShortcut;
95 import com.stoutner.privacybrowser.dialogs.DownloadFile;
96 import com.stoutner.privacybrowser.dialogs.DownloadImage;
97 import com.stoutner.privacybrowser.dialogs.SslCertificateError;
98 import com.stoutner.privacybrowser.dialogs.UrlHistory;
99 import com.stoutner.privacybrowser.dialogs.ViewSslCertificate;
101 import java.io.BufferedReader;
102 import java.io.ByteArrayInputStream;
103 import java.io.IOException;
104 import java.io.InputStreamReader;
105 import java.io.UnsupportedEncodingException;
106 import java.net.MalformedURLException;
108 import java.net.URLEncoder;
109 import java.util.HashMap;
110 import java.util.HashSet;
111 import java.util.Map;
112 import java.util.Set;
114 // We need to use AppCompatActivity from android.support.v7.app.AppCompatActivity to have access to the SupportActionBar until the minimum API is >= 21.
115 public class MainWebView extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CreateHomeScreenShortcut.CreateHomeScreenSchortcutListener,
116 SslCertificateError.SslCertificateErrorListener, DownloadFile.DownloadFileListener, DownloadImage.DownloadImageListener, UrlHistory.UrlHistoryListener {
118 // `appBar` is public static so it can be accessed from `OrbotProxyHelper`.
119 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `closeFindOnPage()`, and `applySettings()`.
120 public static ActionBar appBar;
122 // `favoriteIcon` is public static so it can be accessed from `CreateHomeScreenShortcut`, `Bookmarks`, `CreateBookmark`, `CreateBookmarkFolder`, and `EditBookmark`.
123 // It is also used in `onCreate()` and `onCreateHomeScreenShortcutCreate()`.
124 public static Bitmap favoriteIcon;
126 // `formattedUrlString` is public static so it can be accessed from `Bookmarks`.
127 // It is also used in `onCreate()`, `onOptionsItemSelected()`, `onCreateHomeScreenShortcutCreate()`, and `loadUrlFromTextBox()`.
128 public static String formattedUrlString;
130 // `sslCertificate` is public static so it can be accessed from `ViewSslCertificate`. It is also used in `onCreate()`.
131 public static SslCertificate sslCertificate;
133 // `orbotStatus` is public static so it can be accessed from `OrbotProxyHelper`. It is also used in `onCreate()`.
134 public static String orbotStatus;
137 // `drawerLayout` is used in `onCreate()`, `onNewIntent()`, and `onBackPressed()`.
138 private DrawerLayout drawerLayout;
140 // `rootCoordinatorLayout` is used in `onCreate()` and `applySettings()`.
141 private CoordinatorLayout rootCoordinatorLayout;
143 // 'mainWebView' is used in `onCreate()`, `onOptionsItemSelected()`, `onNavigationItemSelected()`, `onRestart()`, `onCreateContextMenu()`, `findPreviousOnPage()`, `findNextOnPage()`, `closeFindOnPage()`, and `loadUrlFromTextBox()`.
144 private WebView mainWebView;
146 // `fullScreenVideoFrameLayout` is used in `onCreate()` and `onConfigurationChanged()`.
147 private FrameLayout fullScreenVideoFrameLayout;
149 // `swipeRefreshLayout` is used in `onCreate()`, `onPrepareOptionsMenu`, and `onRestart()`.
150 private SwipeRefreshLayout swipeRefreshLayout;
152 // `cookieManager` is used in `onCreate()`, `onOptionsItemSelected()`, and `onNavigationItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `onRestart()`.
153 private CookieManager cookieManager;
155 // `customHeader` is used in `onCreate()`, `onOptionsItemSelected()`, `onCreateContextMenu()`, and `loadUrlFromTextBox()`.
156 private final Map<String, String> customHeaders = new HashMap<>();
158 // `javaScriptEnabled` is also used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `applySettings()`.
159 // It is `Boolean` instead of `boolean` because `applySettings()` needs to know if it is `null`.
160 private Boolean javaScriptEnabled;
162 // `firstPartyCookiesEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, `onDownloadImage()`, `onDownloadFile()`, and `applySettings()`.
163 private boolean firstPartyCookiesEnabled;
165 // `thirdPartyCookiesEnabled` used in `onCreate()`, `onCreateOptionsMenu()`, `onPrepareOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
166 private boolean thirdPartyCookiesEnabled;
168 // `domStorageEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
169 private boolean domStorageEnabled;
171 // `saveFormDataEnabled` is used in `onCreate()`, `onCreateOptionsMenu()`, `onOptionsItemSelected()`, and `applySettings()`.
172 private boolean saveFormDataEnabled;
174 // `swipeToRefreshEnabled` is used in `onPrepareOptionsMenu()` and `applySettings()`.
175 private boolean swipeToRefreshEnabled;
177 // 'homepage' is used in `onCreate()`, `onNavigationItemSelected()`, and `applySettings()`.
178 private String homepage;
180 // `javaScriptDisabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
181 private String javaScriptDisabledSearchURL;
183 // `javaScriptEnabledSearchURL` is used in `loadURLFromTextBox()` and `applySettings()`.
184 private String javaScriptEnabledSearchURL;
186 // `adBlockerEnabled` is used in `onCreate()` and `applySettings()`.
187 private boolean adBlockerEnabled;
189 // `fullScreenBrowsingModeEnabled` is used in `onCreate()` and `applySettings()`.
190 private boolean fullScreenBrowsingModeEnabled;
192 // `inFullScreenBrowsingMode` is used in `onCreate()` and `applySettings()`.
193 private boolean inFullScreenBrowsingMode;
195 // `hideSystemBarsOnFullscreen` is used in `onCreate()` and `applySettings()`.
196 private boolean hideSystemBarsOnFullscreen;
198 // `translucentNavigationBarOnFullscreen` is used in `onCreate()` and `applySettings()`.
199 private boolean translucentNavigationBarOnFullscreen;
201 // `proxyThroughOrbot` is used in `onCreate()` and `applySettings()`
202 private boolean proxyThroughOrbot;
204 // `pendingUrl` is used in `onCreate()` and `applySettings()`
205 private String pendingUrl;
207 // `findOnPageLinearLayout` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
208 private LinearLayout findOnPageLinearLayout;
210 // `findOnPageEditText` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
211 private EditText findOnPageEditText;
213 // `mainMenu` is used in `onCreateOptionsMenu()` and `updatePrivacyIcons()`.
214 private Menu mainMenu;
216 // `drawerToggle` is used in `onCreate()`, `onPostCreate()`, `onConfigurationChanged()`, `onNewIntent()`, and `onNavigationItemSelected()`.
217 private ActionBarDrawerToggle drawerToggle;
219 // `supportAppBar` is used in `onCreate()`, `onOptionsItemSelected()`, and `closeFindOnPage()`.
220 private Toolbar supportAppBar;
222 // `urlTextBox` is used in `onCreate()`, `onOptionsItemSelected()`, and `loadUrlFromTextBox()`.
223 private EditText urlTextBox;
225 // `adView` is used in `onCreate()` and `onConfigurationChanged()`.
228 // `sslErrorHandler` is used in `onCreate()`, `onSslErrorCancel()`, and `onSslErrorProceed`.
229 private SslErrorHandler sslErrorHandler;
231 // `inputMethodManager` is used in `onOptionsItemSelected()`, `loadUrlFromTextBox()`, and `closeFindOnPage()`.
232 private InputMethodManager inputMethodManager;
234 // `mainWebViewRelativeLayout` is used in `onCreate()` and `onNavigationItemSelected()`.
235 private RelativeLayout mainWebViewRelativeLayout;
238 // 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.
239 @SuppressLint("SetJavaScriptEnabled")
240 protected void onCreate(Bundle savedInstanceState) {
241 super.onCreate(savedInstanceState);
242 setContentView(R.layout.drawerlayout);
244 // Get a handle for `inputMethodManager`.
245 inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
247 // We need to use the `SupportActionBar` from `android.support.v7.app.ActionBar` until the minimum API is >= 21.
248 supportAppBar = (Toolbar) findViewById(R.id.app_bar);
249 setSupportActionBar(supportAppBar);
250 appBar = getSupportActionBar();
252 // This is needed to get rid of the Android Studio warning that `appBar` might be null.
253 assert appBar != null;
255 // Add the custom url_app_bar layout, which shows the favoriteIcon, urlTextBar, and progressBar.
256 appBar.setCustomView(R.layout.url_app_bar);
257 appBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
259 // Set the "go" button on the keyboard to load the URL in urlTextBox.
260 urlTextBox = (EditText) appBar.getCustomView().findViewById(R.id.urlTextBox);
261 urlTextBox.setOnKeyListener(new View.OnKeyListener() {
263 public boolean onKey(View v, int keyCode, KeyEvent event) {
264 // If the event is a key-down event on the `enter` button, load the URL.
265 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
266 // Load the URL into the mainWebView and consume the event.
268 loadUrlFromTextBox();
269 } catch (UnsupportedEncodingException e) {
272 // If the enter key was pressed, consume the event.
275 // If any other key was pressed, do not consume the event.
281 // Get handles for views that need to be accessed.
282 drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
283 rootCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.root_coordinatorlayout);
284 mainWebViewRelativeLayout = (RelativeLayout) findViewById(R.id.main_webview_relativelayout);
285 mainWebView = (WebView) findViewById(R.id.mainWebView);
286 findOnPageLinearLayout = (LinearLayout) findViewById(R.id.find_on_page_linearlayout);
287 findOnPageEditText = (EditText) findViewById(R.id.find_on_page_edittext);
288 fullScreenVideoFrameLayout = (FrameLayout) findViewById(R.id.full_screen_video_framelayout);
290 // Create a double-tap listener to toggle full-screen mode.
291 final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
292 // Override `onDoubleTap()`. All other events are handled using the default settings.
294 public boolean onDoubleTap(MotionEvent event) {
295 if (fullScreenBrowsingModeEnabled) { // Only process the double-tap if full screen browsing mode is enabled.
296 // Toggle `inFullScreenBrowsingMode`.
297 inFullScreenBrowsingMode = !inFullScreenBrowsingMode;
299 if (inFullScreenBrowsingMode) { // Switch to full screen mode.
300 // Hide the `appBar`.
303 // Hide the `BannerAd` in the free flavor.
304 if (BuildConfig.FLAVOR.contentEquals("free")) {
305 BannerAd.hideAd(adView);
308 // Modify the system bars.
309 if (hideSystemBarsOnFullscreen) { // Hide everything.
310 // Remove the translucent overlays.
311 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
313 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
314 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
316 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
317 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
318 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
320 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
322 // Set `rootCoordinatorLayout` to fill the whole screen.
323 rootCoordinatorLayout.setFitsSystemWindows(false);
324 } else { // Hide everything except the status and navigation bars.
325 // Set `rootCoordinatorLayout` to fit under the status and navigation bars.
326 rootCoordinatorLayout.setFitsSystemWindows(false);
328 if (translucentNavigationBarOnFullscreen) { // There is an Android Support Library bug that causes a scrim to print on the right side of the `Drawer Layout` when the navigation bar is displayed on the right of the screen.
329 // Set the navigation bar to be translucent.
330 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
333 } else { // Switch to normal viewing mode.
334 // Show the `appBar`.
337 // Show the `BannerAd` in the free flavor.
338 if (BuildConfig.FLAVOR.contentEquals("free")) {
339 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
340 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
342 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
343 adView = findViewById(R.id.adView);
346 // Remove the translucent navigation bar flag if it is set.
347 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
349 // Add the translucent status flag if it is unset. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
350 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
352 // Remove any `SYSTEM_UI` flags from `rootCoordinatorLayout`.
353 rootCoordinatorLayout.setSystemUiVisibility(0);
355 // Constrain `rootCoordinatorLayout` inside the status and navigation bars.
356 rootCoordinatorLayout.setFitsSystemWindows(true);
359 // Consume the double-tap.
361 } else { // Do not consume the double-tap because full screen browsing mode is disabled.
367 // Pass all touch events on `mainWebView` through `gestureDetector` to check for double-taps.
368 mainWebView.setOnTouchListener(new View.OnTouchListener() {
370 public boolean onTouch(View v, MotionEvent event) {
371 // Send the `event` to `gestureDetector`.
372 return gestureDetector.onTouchEvent(event);
376 // Update `findOnPageCountTextView`.
377 mainWebView.setFindListener(new WebView.FindListener() {
378 // Get a handle for `findOnPageCountTextView`.
379 final TextView findOnPageCountTextView = (TextView) findViewById(R.id.find_on_page_count_textview);
382 public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, boolean isDoneCounting) {
383 if ((isDoneCounting) && (numberOfMatches == 0)) { // There are no matches.
384 // Set `findOnPageCountTextView` to `0/0`.
385 findOnPageCountTextView.setText(R.string.zero_of_zero);
386 } else if (isDoneCounting) { // There are matches.
387 // `activeMatchOrdinal` is zero-based.
388 int activeMatch = activeMatchOrdinal + 1;
390 // Set `findOnPageCountTextView`.
391 findOnPageCountTextView.setText(activeMatch + "/" + numberOfMatches);
396 // Search for the string on the page whenever a character changes in the `findOnPageEditText`.
397 findOnPageEditText.addTextChangedListener(new TextWatcher() {
399 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
404 public void onTextChanged(CharSequence s, int start, int before, int count) {
409 public void afterTextChanged(Editable s) {
410 // Search for the text in `mainWebView`.
411 mainWebView.findAllAsync(findOnPageEditText.getText().toString());
415 // Set the `check mark` button for the `findOnPageEditText` keyboard to close the soft keyboard.
416 findOnPageEditText.setOnKeyListener(new View.OnKeyListener() {
418 public boolean onKey(View v, int keyCode, KeyEvent event) {
419 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // The `enter` key was pressed.
420 // Hide the soft keyboard. `0` indicates no additional flags.
421 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
423 // Consume the event.
425 } else { // A different key was pressed.
426 // Do not consume the event.
432 // Implement swipe to refresh
433 swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
434 swipeRefreshLayout.setColorSchemeResources(R.color.blue_700);
435 swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
437 public void onRefresh() {
438 mainWebView.reload();
442 // `DrawerTitle` identifies the `DrawerLayout` in accessibility mode.
443 drawerLayout.setDrawerTitle(GravityCompat.START, getString(R.string.navigation_drawer));
445 // Listen for touches on the navigation menu.
446 final NavigationView navigationView = (NavigationView) findViewById(R.id.navigationview);
447 navigationView.setNavigationItemSelectedListener(this);
449 // Get handles for `navigationMenu` and the back and forward menu items. The menu is zero-based, so items 1, 2, and 3 are the second, third, and fourth entries in the menu.
450 final Menu navigationMenu = navigationView.getMenu();
451 final MenuItem navigationBackMenuItem = navigationMenu.getItem(1);
452 final MenuItem navigationForwardMenuItem = navigationMenu.getItem(2);
453 final MenuItem navigationHistoryMenuItem = navigationMenu.getItem(3);
455 // The `DrawerListener` allows us to update the Navigation Menu.
456 drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
458 public void onDrawerSlide(View drawerView, float slideOffset) {
462 public void onDrawerOpened(View drawerView) {
466 public void onDrawerClosed(View drawerView) {
470 public void onDrawerStateChanged(int newState) {
471 // Update the `Back`, `Forward`, and `History` menu items every time the drawer opens.
472 navigationBackMenuItem.setEnabled(mainWebView.canGoBack());
473 navigationForwardMenuItem.setEnabled(mainWebView.canGoForward());
474 navigationHistoryMenuItem.setEnabled((mainWebView.canGoBack() || mainWebView.canGoForward()));
476 // Hide the keyboard so we can see the navigation menu. `0` indicates no additional flags.
477 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
481 // drawerToggle creates the hamburger icon at the start of the AppBar.
482 drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, supportAppBar, R.string.open_navigation_drawer, R.string.close_navigation_drawer);
484 // Initialize `adServerSet`.
485 final Set<String> adServersSet = new HashSet<>();
487 // Load the list of ad servers into memory.
489 // Load `pgl.yoyo.org_adservers.txt` into a `BufferedReader`.
490 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getAssets().open("pgl.yoyo.org_adservers.txt")));
492 // Create a string for storing each ad server.
495 // Populate `adServersSet`.
496 while ((adServer = bufferedReader.readLine()) != null) {
497 adServersSet.add(adServer);
500 // Close `bufferedReader`.
501 bufferedReader.close();
502 } catch (IOException ioException) {
503 // We're pretty sure the asset exists, so we don't need to worry about the `IOException` ever being thrown.
506 mainWebView.setWebViewClient(new WebViewClient() {
507 // `shouldOverrideUrlLoading` makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
508 // We have to use the deprecated `shouldOverrideUrlLoading` until API >= 24.
509 @SuppressWarnings("deprecation")
511 public boolean shouldOverrideUrlLoading(WebView view, String url) {
512 // Use an external email program if the link begins with `mailto:`.
513 if (url.startsWith("mailto:")) {
514 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
515 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
517 // Parse the url and set it as the data for the `Intent`.
518 emailIntent.setData(Uri.parse(url));
520 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
521 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
524 startActivity(emailIntent);
526 } else { // Load the URL in Privacy Browser.
527 mainWebView.loadUrl(url, customHeaders);
532 // Block ads. We have to use the deprecated `shouldInterceptRequest` until minimum API >= 21.
533 @SuppressWarnings("deprecation")
535 public WebResourceResponse shouldInterceptRequest(WebView view, String url){
536 if (adBlockerEnabled) { // Block ads.
537 // Extract the host from `url`.
538 Uri requestUri = Uri.parse(url);
539 String requestHost = requestUri.getHost();
541 // Create a variable to track if this is an ad server.
542 boolean requestHostIsAdServer = false;
544 // Check all the subdomains of `requestHost` if it is not `null`.
545 if (requestHost != null) {
546 while (requestHost.contains(".")) {
547 if (adServersSet.contains(requestHost)) {
548 requestHostIsAdServer = true;
551 // Strip out the lowest subdomain of `requestHost`.
552 requestHost = requestHost.substring(requestHost.indexOf(".") + 1);
556 if (requestHostIsAdServer) { // It is an ad server.
557 // Return an empty `WebResourceResponse`.
558 return new WebResourceResponse("text/plain", "utf8", new ByteArrayInputStream("".getBytes()));
559 } else { // It is not an ad server.
560 // `return null` loads the requested resource.
563 } else { // Ad blocking is disabled.
564 // `return null` loads the requested resource.
569 // Update the URL in urlTextBox when the page starts to load.
571 public void onPageStarted(WebView view, String url, Bitmap favicon) {
572 // Check to see if we are waiting on Orbot.
573 if (pendingUrl.isEmpty()) { // We are not waiting on Orbot, so we need to process the URL.
574 // We need to update `formattedUrlString` at the beginning of the load, so that if the user toggles JavaScript during the load the new website is reloaded.
575 formattedUrlString = url;
577 // Display the loading URL is the URL text box.
578 urlTextBox.setText(url);
582 // Update formattedUrlString and urlTextBox. It is necessary to do this after the page finishes loading because the final URL can change during load.
584 public void onPageFinished(WebView view, String url) {
585 // Check to see if we are waiting on Orbot.
586 if (pendingUrl.isEmpty()) { // we are not waiting on Orbot, so we need to process the URL.
587 formattedUrlString = url;
589 // Only update urlTextBox if the user is not typing in it.
590 if (!urlTextBox.hasFocus()) {
591 urlTextBox.setText(formattedUrlString);
594 // Store the SSL certificate so it can be accessed from `ViewSslCertificate`.
595 sslCertificate = mainWebView.getCertificate();
599 // Handle SSL Certificate errors.
601 public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
602 // Store `handler` so it can be accesses from `onSslErrorCancel()` and `onSslErrorProceed()`.
603 sslErrorHandler = handler;
605 // Display the SSL error `AlertDialog`.
606 AppCompatDialogFragment sslCertificateErrorDialogFragment = SslCertificateError.displayDialog(error);
607 sslCertificateErrorDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.ssl_certificate_error));
611 mainWebView.setWebChromeClient(new WebChromeClient() {
612 // Update the progress bar when a page is loading.
614 public void onProgressChanged(WebView view, int progress) {
615 ProgressBar progressBar = (ProgressBar) appBar.getCustomView().findViewById(R.id.progressBar);
616 progressBar.setProgress(progress);
617 if (progress < 100) {
618 progressBar.setVisibility(View.VISIBLE);
620 progressBar.setVisibility(View.GONE);
622 //Stop the `SwipeToRefresh` indicator if it is running
623 swipeRefreshLayout.setRefreshing(false);
627 // Set the favorite icon when it changes.
629 public void onReceivedIcon(WebView view, Bitmap icon) {
630 // Save a copy of the favorite icon for use if a shortcut is added to the home screen.
633 // Place the favorite icon in the appBar.
634 ImageView imageViewFavoriteIcon = (ImageView) appBar.getCustomView().findViewById(R.id.favoriteIcon);
635 imageViewFavoriteIcon.setImageBitmap(Bitmap.createScaledBitmap(icon, 64, 64, true));
638 // Enter full screen video
640 public void onShowCustomView(View view, CustomViewCallback callback) {
641 // Pause the ad if this is the free flavor.
642 if (BuildConfig.FLAVOR.contentEquals("free")) {
643 BannerAd.pauseAd(adView);
646 // Remove the translucent overlays.
647 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
649 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
650 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
652 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
653 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
654 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
656 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
658 // Set `rootCoordinatorLayout` to fill the entire screen.
659 rootCoordinatorLayout.setFitsSystemWindows(false);
661 // Add `view` to `fullScreenVideoFrameLayout` and display it on the screen.
662 fullScreenVideoFrameLayout.addView(view);
663 fullScreenVideoFrameLayout.setVisibility(View.VISIBLE);
666 // Exit full screen video
667 public void onHideCustomView() {
668 // Hide `fullScreenVideoFrameLayout`.
669 fullScreenVideoFrameLayout.removeAllViews();
670 fullScreenVideoFrameLayout.setVisibility(View.GONE);
672 // Add the translucent status flag. This also resets `drawerLayout's` `View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN`.
673 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
675 // Set `rootCoordinatorLayout` to fit inside the status and navigation bars. This also clears the `SYSTEM_UI` flags.
676 rootCoordinatorLayout.setFitsSystemWindows(true);
678 // Show the ad if this is the free flavor.
679 if (BuildConfig.FLAVOR.contentEquals("free")) {
680 // Reload the ad. Because the screen may have rotated, we need to use `reloadAfterRotate`.
681 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
683 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
684 adView = findViewById(R.id.adView);
689 // Register `mainWebView` for a context menu. This is used to see link targets and download images.
690 registerForContextMenu(mainWebView);
692 // Allow the downloading of files.
693 mainWebView.setDownloadListener(new DownloadListener() {
695 public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
696 // Show the `DownloadFile` `AlertDialog` and name this instance `@string/download`.
697 AppCompatDialogFragment downloadFileDialogFragment = DownloadFile.fromUrl(url, contentDisposition, contentLength);
698 downloadFileDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
702 // Allow pinch to zoom.
703 mainWebView.getSettings().setBuiltInZoomControls(true);
705 // Hide zoom controls.
706 mainWebView.getSettings().setDisplayZoomControls(false);
708 // Initialize cookieManager.
709 cookieManager = CookieManager.getInstance();
711 // 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).
712 customHeaders.put("X-Requested-With", "");
714 // Set the initial Orbot status.
715 orbotStatus = "unknown";
717 // Create a Orbot status `BroadcastReceiver`.
718 BroadcastReceiver orbotStatusBroadcastReceiver = new BroadcastReceiver() {
720 public void onReceive(Context context, Intent intent) {
721 // Store the content of the status message in `orbotStatus`.
722 orbotStatus = intent.getStringExtra("org.torproject.android.intent.extra.STATUS");
724 // If we are waiting on `pendingUrl`, load it now that Orbot is connected.
725 if (orbotStatus.equals("ON") && !pendingUrl.isEmpty()) {
727 // Wait 500 milliseconds, because Orbot isn't really ready yet.
730 } catch (InterruptedException exception) {
734 // Load `pendingUrl`.
735 formattedUrlString = pendingUrl;
736 mainWebView.loadUrl(formattedUrlString, customHeaders);
738 // Reset `pendingUrl` to be empty.
744 // Register `orbotStatusBroadcastReceiver` on `this` context.
745 this.registerReceiver(orbotStatusBroadcastReceiver, new IntentFilter("org.torproject.android.intent.action.STATUS"));
747 // Initialize the default preference values the first time the program is run. `this` is the context. `false` keeps this command from resetting any current preferences back to default.
748 PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
750 // Apply the settings from the shared preferences.
753 // Get the intent information that started the app.
754 final Intent intent = getIntent();
756 if (intent.getData() != null) {
757 // Get the intent data and convert it to a string.
758 final Uri intentUriData = intent.getData();
759 formattedUrlString = intentUriData.toString();
762 // If formattedUrlString is null assign the homepage to it.
763 if (formattedUrlString == null) {
764 formattedUrlString = homepage;
767 // Initialize `pendingUrl`.
770 if (proxyThroughOrbot & !orbotStatus.equals("ON")) { // We are waiting on Orbot.
771 // Save `formattedUrlString` in `pendingUrl`.
772 pendingUrl = formattedUrlString;
774 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
775 mainWebView.loadData("<html><body><br/><center><h1>Waiting for Orbot to connect...</h1></center></body></html>", "text/html", null);
777 // Load the initial website.
778 mainWebView.loadUrl(formattedUrlString, customHeaders);
781 // If the favorite icon is null, load the default.
782 if (favoriteIcon == null) {
783 // We have to use `ContextCompat` until API >= 21.
784 Drawable favoriteIconDrawable = ContextCompat.getDrawable(getApplicationContext(), R.drawable.world);
785 BitmapDrawable favoriteIconBitmapDrawable = (BitmapDrawable) favoriteIconDrawable;
786 favoriteIcon = favoriteIconBitmapDrawable.getBitmap();
789 // Initialize `inFullScreenBrowsingMode`, which is always false at this point because Privacy Browser never starts in full screen browsing mode.
790 inFullScreenBrowsingMode = false;
792 // Initialize AdView for the free flavor and request an ad. If this is not the free flavor BannerAd.requestAd() does nothing.
793 adView = findViewById(R.id.adView);
794 BannerAd.requestAd(adView);
799 protected void onNewIntent(Intent intent) {
800 // Sets the new intent as the activity intent, so that any future `getIntent()`s pick up this one instead of creating a new activity.
803 if (intent.getData() != null) {
804 // Get the intent data and convert it to a string.
805 final Uri intentUriData = intent.getData();
806 formattedUrlString = intentUriData.toString();
809 // Close the navigation drawer if it is open.
810 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
811 drawerLayout.closeDrawer(GravityCompat.START);
815 mainWebView.loadUrl(formattedUrlString, customHeaders);
817 // Clear the keyboard if displayed and remove the focus on the urlTextBar if it has it.
818 mainWebView.requestFocus();
822 public boolean onCreateOptionsMenu(Menu menu) {
823 // Inflate the menu; this adds items to the action bar if it is present.
824 getMenuInflater().inflate(R.menu.webview_options_menu, menu);
826 // Set mainMenu so it can be used by `onOptionsItemSelected()` and `updatePrivacyIcons`.
829 // Set the initial status of the privacy icons. `false` does not call `invalidateOptionsMenu` as the last step.
830 updatePrivacyIcons(false);
832 // Get handles for the menu items.
833 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
834 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
835 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
836 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
838 // Only display third-Party Cookies if SDK >= 21
839 toggleThirdPartyCookies.setVisible(Build.VERSION.SDK_INT >= 21);
841 // Get the shared preference values. `this` references the current context.
842 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
844 // Set the status of the additional app bar icons. The default is `false`.
845 if (sharedPreferences.getBoolean("display_additional_app_bar_icons", false)) {
846 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
847 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
848 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
849 } else { //Do not display the additional icons.
850 toggleFirstPartyCookies.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
851 toggleDomStorage.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
852 toggleSaveFormData.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
859 public boolean onPrepareOptionsMenu(Menu menu) {
860 // Get handles for the menu items.
861 MenuItem toggleFirstPartyCookies = menu.findItem(R.id.toggleFirstPartyCookies);
862 MenuItem toggleThirdPartyCookies = menu.findItem(R.id.toggleThirdPartyCookies);
863 MenuItem toggleDomStorage = menu.findItem(R.id.toggleDomStorage);
864 MenuItem toggleSaveFormData = menu.findItem(R.id.toggleSaveFormData);
865 MenuItem clearCookies = menu.findItem(R.id.clearCookies);
866 MenuItem clearFormData = menu.findItem(R.id.clearFormData);
867 MenuItem refreshMenuItem = menu.findItem(R.id.refresh);
869 // Set the status of the menu item checkboxes.
870 toggleFirstPartyCookies.setChecked(firstPartyCookiesEnabled);
871 toggleThirdPartyCookies.setChecked(thirdPartyCookiesEnabled);
872 toggleDomStorage.setChecked(domStorageEnabled);
873 toggleSaveFormData.setChecked(saveFormDataEnabled);
875 // Enable third-party cookies if first-party cookies are enabled.
876 toggleThirdPartyCookies.setEnabled(firstPartyCookiesEnabled);
878 // Enable DOM Storage if JavaScript is enabled.
879 toggleDomStorage.setEnabled(javaScriptEnabled);
881 // Enable Clear Cookies if there are any.
882 clearCookies.setEnabled(cookieManager.hasCookies());
884 // Enable Clear Form Data is there is any.
885 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
886 clearFormData.setEnabled(mainWebViewDatabase.hasFormData());
888 // Only show `Refresh` if `swipeToRefresh` is disabled.
889 refreshMenuItem.setVisible(!swipeToRefreshEnabled);
891 // Initialize font size variables.
892 int fontSize = mainWebView.getSettings().getTextZoom();
893 String fontSizeTitle;
894 MenuItem selectedFontSizeMenuItem;
896 // Prepare the font size title and current size menu item.
899 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.fifty_percent);
900 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeFiftyPercent);
904 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.seventy_five_percent);
905 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeSeventyFivePercent);
909 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
910 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
914 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_twenty_five_percent);
915 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredTwentyFivePercent);
919 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_fifty_percent);
920 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredFiftyPercent);
924 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_seventy_five_percent);
925 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredSeventyFivePercent);
929 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.two_hundred_percent);
930 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeTwoHundredPercent);
934 fontSizeTitle = getResources().getString(R.string.font_size) + " - " + getResources().getString(R.string.one_hundred_percent);
935 selectedFontSizeMenuItem = menu.findItem(R.id.fontSizeOneHundredPercent);
939 // Set the font size title and select the current size menu item.
940 MenuItem fontSizeMenuItem = menu.findItem(R.id.fontSize);
941 fontSizeMenuItem.setTitle(fontSizeTitle);
942 selectedFontSizeMenuItem.setChecked(true);
944 // Run all the other default commands.
945 super.onPrepareOptionsMenu(menu);
947 // `return true` displays the menu.
952 // Remove Android Studio's warning about the dangers of using SetJavaScriptEnabled.
953 @SuppressLint("SetJavaScriptEnabled")
954 // removeAllCookies is deprecated, but it is required for API < 21.
955 @SuppressWarnings("deprecation")
956 public boolean onOptionsItemSelected(MenuItem menuItem) {
957 int menuItemId = menuItem.getItemId();
959 // Set the commands that relate to the menu entries.
960 switch (menuItemId) {
961 case R.id.toggleJavaScript:
962 // Switch the status of javaScriptEnabled.
963 javaScriptEnabled = !javaScriptEnabled;
965 // Apply the new JavaScript status.
966 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
968 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
969 updatePrivacyIcons(true);
971 // Display a `Snackbar`.
972 if (javaScriptEnabled) { // JavaScrip is enabled.
973 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_enabled, Snackbar.LENGTH_SHORT).show();
974 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled, but first-party cookies are enabled.
975 Snackbar.make(findViewById(R.id.mainWebView), R.string.javascript_disabled, Snackbar.LENGTH_SHORT).show();
976 } else { // Privacy mode.
977 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
980 // Reload the WebView.
981 mainWebView.reload();
984 case R.id.toggleFirstPartyCookies:
985 // Switch the status of firstPartyCookiesEnabled.
986 firstPartyCookiesEnabled = !firstPartyCookiesEnabled;
988 // Update the menu checkbox.
989 menuItem.setChecked(firstPartyCookiesEnabled);
991 // Apply the new cookie status.
992 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
994 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
995 updatePrivacyIcons(true);
997 // Display a `Snackbar`.
998 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
999 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1000 } else if (javaScriptEnabled){ // JavaScript is still enabled.
1001 Snackbar.make(findViewById(R.id.mainWebView), R.string.first_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1002 } else { // Privacy mode.
1003 Snackbar.make(findViewById(R.id.mainWebView), R.string.privacy_mode, Snackbar.LENGTH_SHORT).show();
1006 // Reload the WebView.
1007 mainWebView.reload();
1010 case R.id.toggleThirdPartyCookies:
1011 if (Build.VERSION.SDK_INT >= 21) {
1012 // Switch the status of thirdPartyCookiesEnabled.
1013 thirdPartyCookiesEnabled = !thirdPartyCookiesEnabled;
1015 // Update the menu checkbox.
1016 menuItem.setChecked(thirdPartyCookiesEnabled);
1018 // Apply the new cookie status.
1019 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1021 // Display a `Snackbar`.
1022 if (thirdPartyCookiesEnabled) {
1023 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_enabled, Snackbar.LENGTH_SHORT).show();
1025 Snackbar.make(findViewById(R.id.mainWebView), R.string.third_party_cookies_disabled, Snackbar.LENGTH_SHORT).show();
1028 // Reload the WebView.
1029 mainWebView.reload();
1030 } // Else do nothing because SDK < 21.
1033 case R.id.toggleDomStorage:
1034 // Switch the status of domStorageEnabled.
1035 domStorageEnabled = !domStorageEnabled;
1037 // Update the menu checkbox.
1038 menuItem.setChecked(domStorageEnabled);
1040 // Apply the new DOM Storage status.
1041 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1043 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1044 updatePrivacyIcons(true);
1046 // Display a `Snackbar`.
1047 if (domStorageEnabled) {
1048 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_enabled, Snackbar.LENGTH_SHORT).show();
1050 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_disabled, Snackbar.LENGTH_SHORT).show();
1053 // Reload the WebView.
1054 mainWebView.reload();
1057 case R.id.toggleSaveFormData:
1058 // Switch the status of saveFormDataEnabled.
1059 saveFormDataEnabled = !saveFormDataEnabled;
1061 // Update the menu checkbox.
1062 menuItem.setChecked(saveFormDataEnabled);
1064 // Apply the new form data status.
1065 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1067 // Display a `Snackbar`.
1068 if (saveFormDataEnabled) {
1069 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_enabled, Snackbar.LENGTH_SHORT).show();
1071 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_disabled, Snackbar.LENGTH_SHORT).show();
1074 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1075 updatePrivacyIcons(true);
1077 // Reload the WebView.
1078 mainWebView.reload();
1081 case R.id.clearCookies:
1082 if (Build.VERSION.SDK_INT < 21) {
1083 cookieManager.removeAllCookie();
1085 cookieManager.removeAllCookies(null);
1087 Snackbar.make(findViewById(R.id.mainWebView), R.string.cookies_deleted, Snackbar.LENGTH_SHORT).show();
1090 case R.id.clearDomStorage:
1091 WebStorage webStorage = WebStorage.getInstance();
1092 webStorage.deleteAllData();
1093 Snackbar.make(findViewById(R.id.mainWebView), R.string.dom_storage_deleted, Snackbar.LENGTH_SHORT).show();
1096 case R.id.clearFormData:
1097 WebViewDatabase mainWebViewDatabase = WebViewDatabase.getInstance(this);
1098 mainWebViewDatabase.clearFormData();
1099 Snackbar.make(findViewById(R.id.mainWebView), R.string.form_data_deleted, Snackbar.LENGTH_SHORT).show();
1102 case R.id.fontSizeFiftyPercent:
1103 mainWebView.getSettings().setTextZoom(50);
1106 case R.id.fontSizeSeventyFivePercent:
1107 mainWebView.getSettings().setTextZoom(75);
1110 case R.id.fontSizeOneHundredPercent:
1111 mainWebView.getSettings().setTextZoom(100);
1114 case R.id.fontSizeOneHundredTwentyFivePercent:
1115 mainWebView.getSettings().setTextZoom(125);
1118 case R.id.fontSizeOneHundredFiftyPercent:
1119 mainWebView.getSettings().setTextZoom(150);
1122 case R.id.fontSizeOneHundredSeventyFivePercent:
1123 mainWebView.getSettings().setTextZoom(175);
1126 case R.id.fontSizeTwoHundredPercent:
1127 mainWebView.getSettings().setTextZoom(200);
1130 case R.id.find_on_page:
1131 // Hide the URL app bar.
1132 supportAppBar.setVisibility(View.GONE);
1134 // Show the Find on Page `RelativeLayout`.
1135 findOnPageLinearLayout.setVisibility(View.VISIBLE);
1137 // Display the keyboard. We have to wait 200 ms before running the command to work around a bug in Android.
1138 // http://stackoverflow.com/questions/5520085/android-show-softkeyboard-with-showsoftinput-is-not-working
1139 findOnPageEditText.postDelayed(new Runnable()
1144 // Set the focus on `findOnPageEditText`.
1145 findOnPageEditText.requestFocus();
1147 // Display the keyboard.
1148 inputMethodManager.showSoftInput(findOnPageEditText, 0);
1154 Intent shareIntent = new Intent();
1155 shareIntent.setAction(Intent.ACTION_SEND);
1156 shareIntent.putExtra(Intent.EXTRA_TEXT, urlTextBox.getText().toString());
1157 shareIntent.setType("text/plain");
1158 startActivity(Intent.createChooser(shareIntent, "Share URL"));
1161 case R.id.addToHomescreen:
1162 // Show the `CreateHomeScreenShortcut` `AlertDialog` and name this instance `R.string.create_shortcut`.
1163 AppCompatDialogFragment createHomeScreenShortcutDialogFragment = new CreateHomeScreenShortcut();
1164 createHomeScreenShortcutDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.create_shortcut));
1166 //Everything else will be handled by `CreateHomeScreenShortcut` and the associated listener below.
1170 // Get a `PrintManager` instance.
1171 PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
1173 // Convert `mainWebView` to `printDocumentAdapter`.
1174 PrintDocumentAdapter printDocumentAdapter = mainWebView.createPrintDocumentAdapter();
1176 // Print the document. The print attributes are `null`.
1177 printManager.print(getResources().getString(R.string.privacy_browser_web_page), printDocumentAdapter, null);
1181 mainWebView.reload();
1185 // Don't consume the event.
1186 return super.onOptionsItemSelected(menuItem);
1190 // removeAllCookies is deprecated, but it is required for API < 21.
1191 @SuppressWarnings("deprecation")
1193 public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
1194 int menuItemId = menuItem.getItemId();
1196 switch (menuItemId) {
1198 mainWebView.loadUrl(homepage, customHeaders);
1202 if (mainWebView.canGoBack()) {
1203 mainWebView.goBack();
1208 if (mainWebView.canGoForward()) {
1209 mainWebView.goForward();
1214 // Gte the `WebBackForwardList`.
1215 WebBackForwardList webBackForwardList = mainWebView.copyBackForwardList();
1217 // Show the `UrlHistory` `AlertDialog` and name this instance `R.string.history`. `this` is the `Context`.
1218 AppCompatDialogFragment urlHistoryDialogFragment = UrlHistory.loadBackForwardList(this, webBackForwardList);
1219 urlHistoryDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.history));
1222 case R.id.bookmarks:
1223 // Launch Bookmarks.
1224 Intent bookmarksIntent = new Intent(this, Bookmarks.class);
1225 startActivity(bookmarksIntent);
1228 case R.id.downloads:
1229 // Launch the system Download Manager.
1230 Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
1232 // Launch as a new task so that Download Manager and Privacy Browser show as separate windows in the recent tasks list.
1233 downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1235 startActivity(downloadManagerIntent);
1239 // Launch `Settings`.
1240 Intent settingsIntent = new Intent(this, Settings.class);
1241 startActivity(settingsIntent);
1246 // Launch `DomainsList`.
1247 Intent domainsIntent = new Intent(this, DomainsList.class);
1248 startActivity(domainsIntent);
1254 Intent guideIntent = new Intent(this, Guide.class);
1255 startActivity(guideIntent);
1260 Intent aboutIntent = new Intent(this, About.class);
1261 startActivity(aboutIntent);
1264 case R.id.clearAndExit:
1265 // Clear cookies. The commands changed slightly in API 21.
1266 if (Build.VERSION.SDK_INT >= 21) {
1267 cookieManager.removeAllCookies(null);
1269 cookieManager.removeAllCookie();
1272 // Clear DOM storage.
1273 WebStorage domStorage = WebStorage.getInstance();
1274 domStorage.deleteAllData();
1277 WebViewDatabase webViewDatabase = WebViewDatabase.getInstance(this);
1278 webViewDatabase.clearFormData();
1280 // Clear cache. The argument of "true" includes disk files.
1281 mainWebView.clearCache(true);
1283 // Clear the back/forward history.
1284 mainWebView.clearHistory();
1286 // Clear any SSL certificate preferences.
1287 mainWebView.clearSslPreferences();
1289 // Clear `formattedUrlString`.
1290 formattedUrlString = null;
1292 // Clear `customHeaders`.
1293 customHeaders.clear();
1295 // Detach all views from `mainWebViewRelativeLayout`.
1296 mainWebViewRelativeLayout.removeAllViews();
1298 // Destroy the internal state of `mainWebView`.
1299 mainWebView.destroy();
1301 // Manually delete the `app_webview` folder, which contains an additional `WebView` cache. See `https://code.google.com/p/android/issues/detail?id=233826&thanks=233826&ts=1486670530`.
1302 Runtime runtime = Runtime.getRuntime();
1303 String dataDirString = getApplicationInfo().dataDir; // `dataDir` will vary, but will be something like `/data/user/0/com.stoutner.privacybrowser.standard`, which links to `/data/data/com.stoutner.privacybrowser.standard`.
1305 runtime.exec("rm -rf " + dataDirString + "/app_webview");
1306 } catch (IOException e) {
1307 // Do nothing if the files do not exist.
1310 // Close Privacy Browser. `finishAndRemoveTask` also removes Privacy Browser from the recent app list.
1311 if (Build.VERSION.SDK_INT >= 21) {
1312 finishAndRemoveTask();
1317 // Remove the terminated program from RAM. The status code is `0`.
1325 // Close the navigation drawer.
1326 drawerLayout.closeDrawer(GravityCompat.START);
1331 public void onPostCreate(Bundle savedInstanceState) {
1332 super.onPostCreate(savedInstanceState);
1334 // Sync the state of the DrawerToggle after onRestoreInstanceState has finished.
1335 drawerToggle.syncState();
1339 public void onConfigurationChanged(Configuration newConfig) {
1340 super.onConfigurationChanged(newConfig);
1342 // Reload the ad for the free flavor if we are not in full screen mode.
1343 if (BuildConfig.FLAVOR.contentEquals("free") && adView.isShown() && !fullScreenVideoFrameLayout.isShown()) {
1345 BannerAd.reloadAfterRotate(adView, getApplicationContext(), getString(R.string.ad_id));
1347 // Reinitialize the `adView` variable, as the `View` will have been removed and re-added by `BannerAd.reloadAfterRotate()`.
1348 adView = findViewById(R.id.adView);
1351 // `invalidateOptionsMenu` should recalculate the number of action buttons from the menu to display on the app bar, but it doesn't because of the this bug: https://code.google.com/p/android/issues/detail?id=20493#c8
1352 // ActivityCompat.invalidateOptionsMenu(this);
1356 public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
1357 // Store the `HitTestResult`.
1358 final WebView.HitTestResult hitTestResult = mainWebView.getHitTestResult();
1361 final String imageUrl;
1362 final String linkUrl;
1364 // Get a handle for the `ClipboardManager`.
1365 final ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
1367 switch (hitTestResult.getType()) {
1368 // `SRC_ANCHOR_TYPE` is a link.
1369 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1370 // Get the target URL.
1371 linkUrl = hitTestResult.getExtra();
1373 // Set the target URL as the title of the `ContextMenu`.
1374 menu.setHeaderTitle(linkUrl);
1376 // Add a `Load URL` entry.
1377 menu.add(R.string.load_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1379 public boolean onMenuItemClick(MenuItem item) {
1380 mainWebView.loadUrl(linkUrl, customHeaders);
1385 // Add a `Copy URL` entry.
1386 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1388 public boolean onMenuItemClick(MenuItem item) {
1389 // Save the link URL in a `ClipData`.
1390 ClipData srcAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), linkUrl);
1392 // Set the `ClipData` as the clipboard's primary clip.
1393 clipboardManager.setPrimaryClip(srcAnchorTypeClipData);
1398 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1399 menu.add(R.string.cancel);
1402 case WebView.HitTestResult.EMAIL_TYPE:
1403 // Get the target URL.
1404 linkUrl = hitTestResult.getExtra();
1406 // Set the target URL as the title of the `ContextMenu`.
1407 menu.setHeaderTitle(linkUrl);
1409 // Add a `Write Email` entry.
1410 menu.add(R.string.write_email).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1412 public boolean onMenuItemClick(MenuItem item) {
1413 // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
1414 Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
1416 // Parse the url and set it as the data for the `Intent`.
1417 emailIntent.setData(Uri.parse("mailto:" + linkUrl));
1419 // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of Privacy Browser.
1420 emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1423 startActivity(emailIntent);
1428 // Add a `Copy Email Address` entry.
1429 menu.add(R.string.copy_email_address).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1431 public boolean onMenuItemClick(MenuItem item) {
1432 // Save the email address in a `ClipData`.
1433 ClipData srcEmailTypeClipData = ClipData.newPlainText(getResources().getString(R.string.email_address), linkUrl);
1435 // Set the `ClipData` as the clipboard's primary clip.
1436 clipboardManager.setPrimaryClip(srcEmailTypeClipData);
1441 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1442 menu.add(R.string.cancel);
1445 // `IMAGE_TYPE` is an image.
1446 case WebView.HitTestResult.IMAGE_TYPE:
1447 // Get the image URL.
1448 imageUrl = hitTestResult.getExtra();
1450 // Set the image URL as the title of the `ContextMenu`.
1451 menu.setHeaderTitle(imageUrl);
1453 // Add a `View Image` entry.
1454 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1456 public boolean onMenuItemClick(MenuItem item) {
1457 mainWebView.loadUrl(imageUrl, customHeaders);
1462 // Add a `Download Image` entry.
1463 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1465 public boolean onMenuItemClick(MenuItem item) {
1466 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1467 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1468 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1473 // Add a `Copy URL` entry.
1474 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1476 public boolean onMenuItemClick(MenuItem item) {
1477 // Save the image URL in a `ClipData`.
1478 ClipData srcImageTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1480 // Set the `ClipData` as the clipboard's primary clip.
1481 clipboardManager.setPrimaryClip(srcImageTypeClipData);
1486 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1487 menu.add(R.string.cancel);
1491 // `SRC_IMAGE_ANCHOR_TYPE` is an image that is also a link.
1492 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1493 // Get the image URL.
1494 imageUrl = hitTestResult.getExtra();
1496 // Set the image URL as the title of the `ContextMenu`.
1497 menu.setHeaderTitle(imageUrl);
1499 // Add a `View Image` entry.
1500 menu.add(R.string.view_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1502 public boolean onMenuItemClick(MenuItem item) {
1503 mainWebView.loadUrl(imageUrl, customHeaders);
1508 // Add a `Download Image` entry.
1509 menu.add(R.string.download_image).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1511 public boolean onMenuItemClick(MenuItem item) {
1512 // Show the `DownloadImage` `AlertDialog` and name this instance `@string/download`.
1513 AppCompatDialogFragment downloadImageDialogFragment = DownloadImage.imageUrl(imageUrl);
1514 downloadImageDialogFragment.show(getSupportFragmentManager(), getResources().getString(R.string.download));
1519 // Add a `Copy URL` entry.
1520 menu.add(R.string.copy_url).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
1522 public boolean onMenuItemClick(MenuItem item) {
1523 // Save the image URL in a `ClipData`.
1524 ClipData srcImageAnchorTypeClipData = ClipData.newPlainText(getResources().getString(R.string.url), imageUrl);
1526 // Set the `ClipData` as the clipboard's primary clip.
1527 clipboardManager.setPrimaryClip(srcImageAnchorTypeClipData);
1532 // Add a `Cancel` entry, which by default closes the `ContextMenu`.
1533 menu.add(R.string.cancel);
1539 public void onCreateHomeScreenShortcut(AppCompatDialogFragment dialogFragment) {
1540 // Get shortcutNameEditText from the alert dialog.
1541 EditText shortcutNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.shortcut_name_edittext);
1543 // Create the bookmark shortcut based on formattedUrlString.
1544 Intent bookmarkShortcut = new Intent();
1545 bookmarkShortcut.setAction(Intent.ACTION_VIEW);
1546 bookmarkShortcut.setData(Uri.parse(formattedUrlString));
1548 // Place the bookmark shortcut on the home screen.
1549 Intent placeBookmarkShortcut = new Intent();
1550 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.INTENT", bookmarkShortcut);
1551 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.NAME", shortcutNameEditText.getText().toString());
1552 placeBookmarkShortcut.putExtra("android.intent.extra.shortcut.ICON", favoriteIcon);
1553 placeBookmarkShortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
1554 sendBroadcast(placeBookmarkShortcut);
1558 public void onDownloadImage(AppCompatDialogFragment dialogFragment, String imageUrl) {
1559 // Download the image if it has an HTTP or HTTPS URI.
1560 if (imageUrl.startsWith("http")) {
1561 // Get a handle for the system `DOWNLOAD_SERVICE`.
1562 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1564 // Parse `imageUrl`.
1565 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(imageUrl));
1567 // Pass cookies to download manager if cookies are enabled. This is required to download images from websites that require a login.
1568 if (firstPartyCookiesEnabled) {
1569 // Get the cookies for `imageUrl`.
1570 String cookies = cookieManager.getCookie(imageUrl);
1572 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1573 downloadRequest.addRequestHeader("Cookie", cookies);
1576 // Get the file name from `dialogFragment`.
1577 EditText downloadImageNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_image_name);
1578 String imageName = downloadImageNameEditText.getText().toString();
1580 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1581 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download save in the the `DIRECTORY_DOWNLOADS` using `imageName`.
1582 downloadRequest.setDestinationInExternalFilesDir(this, "/", imageName);
1583 } else { // Only set the title using `imageName`.
1584 downloadRequest.setTitle(imageName);
1587 // Allow `MediaScanner` to index the download if it is a media file.
1588 downloadRequest.allowScanningByMediaScanner();
1590 // Add the URL as the description for the download.
1591 downloadRequest.setDescription(imageUrl);
1593 // Show the download notification after the download is completed.
1594 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1596 // Initiate the download.
1597 downloadManager.enqueue(downloadRequest);
1598 } else { // The image is not an HTTP or HTTPS URI.
1599 Snackbar.make(mainWebView, R.string.cannot_download_image, Snackbar.LENGTH_INDEFINITE).show();
1604 public void onDownloadFile(AppCompatDialogFragment dialogFragment, String downloadUrl) {
1605 // Download the file if it has an HTTP or HTTPS URI.
1606 if (downloadUrl.startsWith("http")) {
1608 // Get a handle for the system `DOWNLOAD_SERVICE`.
1609 DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
1611 // Parse `downloadUrl`.
1612 DownloadManager.Request downloadRequest = new DownloadManager.Request(Uri.parse(downloadUrl));
1614 // Pass cookies to download manager if cookies are enabled. This is required to download files from websites that require a login.
1615 if (firstPartyCookiesEnabled) {
1616 // Get the cookies for `downloadUrl`.
1617 String cookies = cookieManager.getCookie(downloadUrl);
1619 // Add the cookies to `downloadRequest`. In the HTTP request header, cookies are named `Cookie`.
1620 downloadRequest.addRequestHeader("Cookie", cookies);
1623 // Get the file name from `dialogFragment`.
1624 EditText downloadFileNameEditText = (EditText) dialogFragment.getDialog().findViewById(R.id.download_file_name);
1625 String fileName = downloadFileNameEditText.getText().toString();
1627 // Once we have `WRITE_EXTERNAL_STORAGE` permissions we can use `setDestinationInExternalPublicDir`.
1628 if (Build.VERSION.SDK_INT >= 23) { // If API >= 23, set the download location to `/sdcard/Android/data/com.stoutner.privacybrowser.standard/files` named `fileName`.
1629 downloadRequest.setDestinationInExternalFilesDir(this, "/", fileName);
1630 } else { // Only set the title using `fileName`.
1631 downloadRequest.setTitle(fileName);
1634 // Allow `MediaScanner` to index the download if it is a media file.
1635 downloadRequest.allowScanningByMediaScanner();
1637 // Add the URL as the description for the download.
1638 downloadRequest.setDescription(downloadUrl);
1640 // Show the download notification after the download is completed.
1641 downloadRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
1643 // Initiate the download.
1644 downloadManager.enqueue(downloadRequest);
1645 } else { // The download is not an HTTP or HTTPS URI.
1646 Snackbar.make(mainWebView, R.string.cannot_download_file, Snackbar.LENGTH_INDEFINITE).show();
1650 public void viewSslCertificate(View view) {
1651 // Show the `ViewSslCertificate` `AlertDialog` and name this instance `@string/view_ssl_certificate`.
1652 DialogFragment viewSslCertificateDialogFragment = new ViewSslCertificate();
1653 viewSslCertificateDialogFragment.show(getFragmentManager(), getResources().getString(R.string.view_ssl_certificate));
1657 public void onSslErrorCancel() {
1658 sslErrorHandler.cancel();
1662 public void onSslErrorProceed() {
1663 sslErrorHandler.proceed();
1667 public void onUrlHistoryEntrySelected(int moveBackOrForwardSteps) {
1668 // Load the history entry.
1669 mainWebView.goBackOrForward(moveBackOrForwardSteps);
1673 public void onClearHistory() {
1674 // Clear the history.
1675 mainWebView.clearHistory();
1678 // Override `onBackPressed` to handle the navigation drawer and `mainWebView`.
1680 public void onBackPressed() {
1681 // Close the navigation drawer if it is available. GravityCompat.START is the drawer on the left on Left-to-Right layout text.
1682 if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
1683 drawerLayout.closeDrawer(GravityCompat.START);
1685 // Load the previous URL if available.
1686 if (mainWebView.canGoBack()) {
1687 mainWebView.goBack();
1689 // Pass `onBackPressed()` to the system.
1690 super.onBackPressed();
1696 public void onPause() {
1697 // Pause `mainWebView`.
1698 mainWebView.onPause();
1700 // Stop all JavaScript.
1701 mainWebView.pauseTimers();
1703 // Pause the adView or it will continue to consume resources in the background on the free flavor.
1704 if (BuildConfig.FLAVOR.contentEquals("free")) {
1705 BannerAd.pauseAd(adView);
1712 public void onResume() {
1715 // Resume JavaScript (if enabled).
1716 mainWebView.resumeTimers();
1718 // Resume `mainWebView`.
1719 mainWebView.onResume();
1721 // Resume the adView for the free flavor.
1722 if (BuildConfig.FLAVOR.contentEquals("free")) {
1723 BannerAd.resumeAd(adView);
1728 public void onRestart() {
1731 // Apply the settings from shared preferences, which might have been changed in `Settings`.
1734 // Update the privacy icon. `true` runs `invalidateOptionsMenu` as the last step.
1735 updatePrivacyIcons(true);
1739 private void loadUrlFromTextBox() throws UnsupportedEncodingException {
1740 // Get the text from urlTextBox and convert it to a string. trim() removes white spaces from the beginning and end of the string.
1741 String unformattedUrlString = urlTextBox.getText().toString().trim();
1743 URL unformattedUrl = null;
1744 Uri.Builder formattedUri = new Uri.Builder();
1746 // Check to see if unformattedUrlString is a valid URL. Otherwise, convert it into a Duck Duck Go search.
1747 if (Patterns.WEB_URL.matcher(unformattedUrlString).matches()) {
1748 // Add http:// at the beginning if it is missing. Otherwise the app will segfault.
1749 if (!unformattedUrlString.startsWith("http")) {
1750 unformattedUrlString = "http://" + unformattedUrlString;
1753 // 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.
1755 unformattedUrl = new URL(unformattedUrlString);
1756 } catch (MalformedURLException e) {
1757 e.printStackTrace();
1760 // The ternary operator (? :) makes sure that a null pointer exception is not thrown, which would happen if .get was called on a null value.
1761 final String scheme = unformattedUrl != null ? unformattedUrl.getProtocol() : null;
1762 final String authority = unformattedUrl != null ? unformattedUrl.getAuthority() : null;
1763 final String path = unformattedUrl != null ? unformattedUrl.getPath() : null;
1764 final String query = unformattedUrl != null ? unformattedUrl.getQuery() : null;
1765 final String fragment = unformattedUrl != null ? unformattedUrl.getRef() : null;
1767 formattedUri.scheme(scheme).authority(authority).path(path).query(query).fragment(fragment);
1768 formattedUrlString = formattedUri.build().toString();
1770 // Sanitize the search input and convert it to a DuckDuckGo search.
1771 final String encodedUrlString = URLEncoder.encode(unformattedUrlString, "UTF-8");
1773 // Use the correct search URL.
1774 if (javaScriptEnabled) { // JavaScript is enabled.
1775 formattedUrlString = javaScriptEnabledSearchURL + encodedUrlString;
1776 } else { // JavaScript is disabled.
1777 formattedUrlString = javaScriptDisabledSearchURL + encodedUrlString;
1781 mainWebView.loadUrl(formattedUrlString, customHeaders);
1783 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1784 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1787 public void findPreviousOnPage(View view) {
1788 // Go to the previous highlighted phrase on the page. `false` goes backwards instead of forwards.
1789 mainWebView.findNext(false);
1792 public void findNextOnPage(View view) {
1793 // Go to the next highlighted phrase on the page. `true` goes forwards instead of backwards.
1794 mainWebView.findNext(true);
1797 public void closeFindOnPage(View view) {
1798 // Delete the contents of `find_on_page_edittext`.
1799 findOnPageEditText.setText(null);
1801 // Clear the highlighted phrases.
1802 mainWebView.clearMatches();
1804 // Hide the Find on Page `RelativeLayout`.
1805 findOnPageLinearLayout.setVisibility(View.GONE);
1807 // Show the URL app bar.
1808 supportAppBar.setVisibility(View.VISIBLE);
1810 // Hide the keyboard so we can see the webpage. `0` indicates no additional flags.
1811 inputMethodManager.hideSoftInputFromWindow(mainWebView.getWindowToken(), 0);
1814 private void applySettings() {
1815 // Get the shared preference values. `this` references the current context.
1816 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
1818 // Store the values from `sharedPreferences` in variables.
1819 String userAgentString = sharedPreferences.getString("user_agent", "PrivacyBrowser/1.0");
1820 String customUserAgentString = sharedPreferences.getString("custom_user_agent", "PrivacyBrowser/1.0");
1821 String javaScriptDisabledSearchString = sharedPreferences.getString("javascript_disabled_search", "https://duckduckgo.com/html/?q=");
1822 String javaScriptDisabledSearchCustomURLString = sharedPreferences.getString("javascript_disabled_search_custom_url", "");
1823 String javaScriptEnabledSearchString = sharedPreferences.getString("javascript_enabled_search", "https://duckduckgo.com/?q=");
1824 String javaScriptEnabledSearchCustomURLString = sharedPreferences.getString("javascript_enabled_search_custom_url", "");
1825 String homepageString = sharedPreferences.getString("homepage", "https://www.duckduckgo.com");
1826 String torHomepageString = sharedPreferences.getString("tor_homepage", "https://3g2upl4pq6kufc4m.onion");
1827 String torJavaScriptDisabledSearchString = sharedPreferences.getString("tor_javascript_disabled_search", "https://3g2upl4pq6kufc4m.onion/html/?q=");
1828 String torJavaScriptDisabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_disabled_search_custom_url", "");
1829 String torJavaScriptEnabledSearchString = sharedPreferences.getString("tor_javascript_enabled_search", "https://3g2upl4pq6kufc4m.onion/?q=");
1830 String torJavaScriptEnabledSearchCustomURLString = sharedPreferences.getString("tor_javascript_enabled_search_custom_url", "");
1831 String defaultFontSizeString = sharedPreferences.getString("default_font_size", "100");
1832 swipeToRefreshEnabled = sharedPreferences.getBoolean("swipe_to_refresh_enabled", false);
1833 adBlockerEnabled = sharedPreferences.getBoolean("block_ads", true);
1834 boolean doNotTrackEnabled = sharedPreferences.getBoolean("do_not_track", false);
1835 proxyThroughOrbot = sharedPreferences.getBoolean("proxy_through_orbot", false);
1836 fullScreenBrowsingModeEnabled = sharedPreferences.getBoolean("enable_full_screen_browsing_mode", false);
1837 hideSystemBarsOnFullscreen = sharedPreferences.getBoolean("hide_system_bars", false);
1838 translucentNavigationBarOnFullscreen = sharedPreferences.getBoolean("translucent_navigation_bar", true);
1840 // Because they can be modified on-the-fly by the user, these default settings are only applied when the program first runs.
1841 if (javaScriptEnabled == null) { // If `javaScriptEnabled` is null the program is just starting.
1842 // Get the values from `sharedPreferences`.
1843 javaScriptEnabled = sharedPreferences.getBoolean("javascript_enabled", false);
1844 firstPartyCookiesEnabled = sharedPreferences.getBoolean("first_party_cookies_enabled", false);
1845 thirdPartyCookiesEnabled = sharedPreferences.getBoolean("third_party_cookies_enabled", false);
1846 domStorageEnabled = sharedPreferences.getBoolean("dom_storage_enabled", false);
1847 saveFormDataEnabled = sharedPreferences.getBoolean("save_form_data_enabled", false);
1849 // Apply the default settings.
1850 mainWebView.getSettings().setJavaScriptEnabled(javaScriptEnabled);
1851 cookieManager.setAcceptCookie(firstPartyCookiesEnabled);
1852 mainWebView.getSettings().setDomStorageEnabled(domStorageEnabled);
1853 mainWebView.getSettings().setSaveFormData(saveFormDataEnabled);
1854 mainWebView.getSettings().setTextZoom(Integer.valueOf(defaultFontSizeString));
1856 // Set third-party cookies status if API >= 21.
1857 if (Build.VERSION.SDK_INT >= 21) {
1858 cookieManager.setAcceptThirdPartyCookies(mainWebView, thirdPartyCookiesEnabled);
1862 // Set the homepage, search, and proxy options.
1863 if (proxyThroughOrbot) { // Set the Tor options.
1864 // Set `torHomepageString` as `homepage`.
1865 homepage = torHomepageString;
1867 // Set JavaScript disabled search.
1868 if (torJavaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1869 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchCustomURLString;
1870 } else { // Use the string from the pre-built list.
1871 javaScriptDisabledSearchURL = torJavaScriptDisabledSearchString;
1874 // Set JavaScript enabled search.
1875 if (torJavaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1876 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchCustomURLString;
1877 } else { // Use the string from the pre-built list.
1878 javaScriptEnabledSearchURL = torJavaScriptEnabledSearchString;
1881 // Set the proxy. `this` refers to the current activity where an `AlertDialog` might be displayed.
1882 OrbotProxyHelper.setProxy(getApplicationContext(), this, "localhost", "8118");
1883 } else { // Set the non-Tor options.
1884 // Set `homepageString` as `homepage`.
1885 homepage = homepageString;
1887 // Set JavaScript disabled search.
1888 if (javaScriptDisabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1889 javaScriptDisabledSearchURL = javaScriptDisabledSearchCustomURLString;
1890 } else { // Use the string from the pre-built list.
1891 javaScriptDisabledSearchURL = javaScriptDisabledSearchString;
1894 // Set JavaScript enabled search.
1895 if (javaScriptEnabledSearchString.equals("Custom URL")) { // Get the custom URL string.
1896 javaScriptEnabledSearchURL = javaScriptEnabledSearchCustomURLString;
1897 } else { // Use the string from the pre-built list.
1898 javaScriptEnabledSearchURL = javaScriptEnabledSearchString;
1901 // Reset the proxy to default. The host is `""` and the port is `"0"`.
1902 OrbotProxyHelper.setProxy(getApplicationContext(), this, "", "0");
1905 // Set swipe to refresh.
1906 swipeRefreshLayout.setEnabled(swipeToRefreshEnabled);
1908 // Set the user agent initial status.
1909 switch (userAgentString) {
1910 case "Default user agent":
1911 // Set the user agent to `""`, which uses the default value.
1912 mainWebView.getSettings().setUserAgentString("");
1915 case "Custom user agent":
1916 // Set the custom user agent.
1917 mainWebView.getSettings().setUserAgentString(customUserAgentString);
1921 // Use the selected user agent.
1922 mainWebView.getSettings().setUserAgentString(userAgentString);
1926 // Set Do Not Track status.
1927 if (doNotTrackEnabled) {
1928 customHeaders.put("DNT", "1");
1930 customHeaders.remove("DNT");
1933 // If we are in full screen mode update the `SYSTEM_UI` flags.
1934 if (inFullScreenBrowsingMode) {
1935 if (hideSystemBarsOnFullscreen) { // Hide everything.
1936 // Remove the translucent navigation setting if it is currently flagged.
1937 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1939 // Remove the translucent status bar overlay.
1940 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1942 // Remove the translucent status bar overlay on the `Drawer Layout`, which is special and needs its own command.
1943 drawerLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1945 /* SYSTEM_UI_FLAG_FULLSCREEN hides the status bar at the top of the screen.
1946 * SYSTEM_UI_FLAG_HIDE_NAVIGATION hides the navigation bar on the bottom or right of the screen.
1947 * SYSTEM_UI_FLAG_IMMERSIVE_STICKY makes the status and navigation bars translucent and automatically rehides them after they are shown.
1949 rootCoordinatorLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
1950 } else { // Hide everything except the status and navigation bars.
1951 // Add the translucent status flag if it is unset.
1952 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
1954 if (translucentNavigationBarOnFullscreen) {
1955 // Set the navigation bar to be translucent.
1956 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1958 // Set the navigation bar to be black.
1959 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
1964 if (proxyThroughOrbot & !orbotStatus.equals("ON")) { // We are waiting on Orbot.
1965 // Save `formattedUrlString` in `pendingUrl`.
1966 pendingUrl = formattedUrlString;
1968 // Load a waiting page. `null` specifies no encoding, which defaults to ASCII.
1969 mainWebView.loadData("<html><body><br/><center><h1>Waiting for Orbot to connect...</h1></center></body></html>", "text/html", null);
1973 private void updatePrivacyIcons(boolean runInvalidateOptionsMenu) {
1974 // Get handles for the icons.
1975 MenuItem privacyIcon = mainMenu.findItem(R.id.toggleJavaScript);
1976 MenuItem firstPartyCookiesIcon = mainMenu.findItem(R.id.toggleFirstPartyCookies);
1977 MenuItem domStorageIcon = mainMenu.findItem(R.id.toggleDomStorage);
1978 MenuItem formDataIcon = mainMenu.findItem(R.id.toggleSaveFormData);
1980 // Update `privacyIcon`.
1981 if (javaScriptEnabled) { // JavaScript is enabled.
1982 privacyIcon.setIcon(R.drawable.javascript_enabled);
1983 } else if (firstPartyCookiesEnabled) { // JavaScript is disabled but cookies are enabled.
1984 privacyIcon.setIcon(R.drawable.warning);
1985 } else { // All the dangerous features are disabled.
1986 privacyIcon.setIcon(R.drawable.privacy_mode);
1989 // Update `firstPartyCookiesIcon`.
1990 if (firstPartyCookiesEnabled) { // First-party cookies are enabled.
1991 firstPartyCookiesIcon.setIcon(R.drawable.cookies_enabled);
1992 } else { // First-party cookies are disabled.
1993 firstPartyCookiesIcon.setIcon(R.drawable.cookies_disabled);
1996 // Update `domStorageIcon`.
1997 if (javaScriptEnabled && domStorageEnabled) { // Both JavaScript and DOM storage are enabled.
1998 domStorageIcon.setIcon(R.drawable.dom_storage_enabled);
1999 } else if (javaScriptEnabled) { // JavaScript is enabled but DOM storage is disabled.
2000 domStorageIcon.setIcon(R.drawable.dom_storage_disabled);
2001 } else { // JavaScript is disabled, so DOM storage is ghosted.
2002 domStorageIcon.setIcon(R.drawable.dom_storage_ghosted);
2005 // Update `formDataIcon`.
2006 if (saveFormDataEnabled) { // Form data is enabled.
2007 formDataIcon.setIcon(R.drawable.form_data_enabled);
2008 } else { // Form data is disabled.
2009 formDataIcon.setIcon(R.drawable.form_data_disabled);
2012 // `invalidateOptionsMenu` calls `onPrepareOptionsMenu()` and redraws the icons in the `AppBar`. `this` references the current activity.
2013 if (runInvalidateOptionsMenu) {
2014 ActivityCompat.invalidateOptionsMenu(this);